
import at.clockwork.time.domain.*
import at.clockwork.transfer.gwtTransfer.client.enumeration.TimeModelDayEnum

import java.io.*
import java.nio.charset.*
import java.text.SimpleDateFormat

class ImportPublicHolidaysService {

	static transactional = false //TODO = true

	List regionList = [

		[name: "A", description:"Österreich", geo:3058]

		,[name: "D-BW", description:"Baden-Würtemberg", geo:3060]
		,[name: "D-BY", description:"Bayern", geo:3061]
		,[name: "D-BE", description:"Berlin", geo:3062]
		,[name: "D-BB", description:"Brandenburg", geo:3063]
		,[name: "D-HB", description:"Bremen", geo:3064]
		,[name: "D-HH", description:"Hamburg", geo:3065]
		,[name: "D-HE", description:"Hessen", geo:3066]
		,[name: "D-MV", description:"Mecklenburg Vorpommern", geo:3067]
		,[name: "D-NI", description:"Niedersachsen", geo:3068]
		,[name: "D-NW", description:"Nordrhein-Westfalen", geo:3069]
		,[name: "D-RP", description:"Reinland-Pfalz", geo:3070]
		,[name: "D-SL", description:"Saarland", geo:3071]
		,[name: "D-SN", description:"Sachsen", geo:3072]
		,[name: "D-ST", description:"Sachsen-Anhalt", geo:3073]
		,[name: "D-SH", description:"Schleswig-Holstein", geo:3074]
		,[name: "D-TH", description:"Thüringen", geo:3075]

		,[name: "CH-AG", description:"Aargau", geo:1]
		,[name: "CH-AR", description:"Appenzell-Außerrhoden", geo:245]
		,[name: "CH-AI", description:"Appenzell-Innerrohden", geo:266]
		,[name: "CH-BL", description:"Basel-Landschaft", geo:273]
		,[name: "CH-BS", description:"Basel-Stadt", geo:365]
		,[name: "CH-BE", description:"Bern", geo:369]
		,[name: "CH-FR", description:"Freiburg", geo:796]
		,[name: "CH-GE", description:"Genf", geo:1026]
		,[name: "CH-GL", description:"Glarus", geo:1072]
		,[name: "CH-GR", description:"Graubünden", geo:1102]
		,[name: "CH-JU", description:"Jura", geo:1323]
		,[name: "CH-LU", description:"Luzern", geo:1410]
		,[name: "CH-NE", description:"Neuenburg", geo:1523]
		,[name: "CH-NW", description:"Nidwalden", geo:1592]
		,[name: "CH-OW", description:"Obwalden", geo:1604]
		,[name: "CH-SH", description:"Schaffhausen", geo:1612]
		,[name: "CH-SZ", description:"Schwyz", geo:1653]
		,[name: "CH-SO", description:"Solothurn", geo:1690]
		,[name: "CH-SG", description:"St. Gallen", geo:1827]
		,[name: "CH-TI", description:"Tessin", geo:1932]
		,[name: "CH-TG", description:"Thurgau", geo:2173]
		,[name: "CH-UR", description:"Uri", geo:2262]
		,[name: "CH-VD", description:"Waadt", geo:2283]
		,[name: "CH-VS", description:"Wallis", geo:2685]
		,[name: "CH-ZG", description:"Zug", geo:2860]
		,[name: "CH-ZH", description:"Zürich", geo:2872]
		
		,[name: "FL", description:"Fürstentum Liechtenstein", geo:3057]

       	,[name: "I-T_ST", description:"Trentino-Südtirol", geo:3434]
       	
	]
	
	int startYear = 2020
	int endYear = 2034
	String dateFormat = "dd.MM.yyyy"
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat)
							
	def run() {

		if (false) {
			regionList.each { Map regionMap ->
				if (!Region.findWhere(name:regionMap.name, deleted:false)) {
					new Region(name:regionMap.name, description:regionMap.description).save()
				}
			}
		}
		
		Region.findAllWhere(deleted:false).each { Region region ->

			Map data = regionList.find { it.name == region.name }
			if (data) {
				for (int year : startYear .. endYear) {
					getData(region, data.geo, year)
				}
			}
		
		}

	}
	
	
	void getData(Region region, int geo, int year) {
	
		List allowedItemList = ["1", "2"]
		
		println """
Daten: ${region.name}, geo=$geo, year=$year
====================================="""
		
		String url = "https://www.feiertagskalender.ch/index.php?geo=$geo&jahr=$year"
		String data = getDataFromUrl(url)
		
		String startBodySearch = "<tbody>"
		String endBodySearch = "</tbody>"
		String startRowSearch = "<tr class"
		String endRowSearch = "</tr>"
		String startDateSearch = "<td><span class=\"dark\">"
		String endDateSearch = "</span></td>"
		String startNameSearch = "\">"
		String endNameSearch = "</a>"
		String startKennzeichenSearch = "\">"
		String endKennzeichenSearch = "</span>"
		
		int startBody = data.indexOf(startBodySearch)
		int endBody = data.indexOf(endBodySearch, startBody)
		if (startBody > 0 && endBody > 0 && endBody > startBody) {
		
			String body = data[startBody .. endBody+endBodySearch.size()]
			while (body.size() > 0) {
				
				int startRow = body.indexOf(startRowSearch)
				int endRow = body.indexOf(endRowSearch, startRow)
				if (startRow > 0 && endRow > 0 && endRow > startRow) {
					
					String tr = body[startRow .. endRow+endRowSearch.size()]
					
					if (tr && tr.size() > 0) {
					
						int startDate = tr.indexOf(startDateSearch)
						int endDate = tr.indexOf(endDateSearch, startDate)
						if (startDate > 0 && endDate > 0 && endDate > startDate) {
						
							String dateString = tr[startDate+startDateSearch.size() .. endDate-1].trim()
							Date date = simpleDateFormat.parse(dateString)
							
							tr = tr[endDate+endDateSearch.size()..-1]
							
							int startDummy = tr.indexOf("<td")
							int endDummy = tr.indexOf("</td", startDummy)
							if (startDummy > 0 && endDummy > 0 && endDummy > startDummy) {
								tr = tr[endDummy+2..-1]
							}
							
							int startName = tr.indexOf(startNameSearch)
							int endName = tr.indexOf(endNameSearch, startName)
							if (startName > 0 && endName > 0 && endName > startName) {
							
								String name = tr[startName+startNameSearch.size() .. endName-1].trim()
								tr = tr[endName+endNameSearch.size()..-1]
								
								startDummy = tr.indexOf("<td")
								endDummy = tr.indexOf("</td", startDummy)
								if (startDummy > 0 && endDummy > 0 && endDummy > startDummy) {
									tr = tr[endDummy+2..-1]
								}
								
								int startKennzeichen = tr.indexOf(startKennzeichenSearch)
								int endKennzeichen = tr.indexOf(endKennzeichenSearch, startKennzeichen)
								
								if (startKennzeichen > 0 && endKennzeichen > 0 && endKennzeichen > startKennzeichen) {
								
									String kennzeichen = tr[startKennzeichen+startKennzeichenSearch.size() .. endKennzeichen-1].trim()
									if (allowedItemList.any{it == kennzeichen}) {
										
										println "date=$date, kennzeichen=$kennzeichen, name=$name"
										
										PublicHoliday publicHoliday = PublicHoliday.findWhere(date:date, deleted:false)
										if (!publicHoliday) {
											publicHoliday = new PublicHoliday(date:date)
										}
										publicHoliday.description = name
										publicHoliday.save()

										Religion.findAllWhere(deleted:false).each { Religion religion ->
										
											PublicHoliday2Detail publicHoliday2Detail = PublicHoliday2Detail.findWhere(publicHoliday:publicHoliday, region:region, religion:religion)
											if (!publicHoliday2Detail) {
												publicHoliday2Detail = new PublicHoliday2Detail(publicHoliday:publicHoliday, region:region, religion:religion)
												publicHoliday2Detail.dayEnum = TimeModelDayEnum.HOLIDAY_1
												publicHoliday2Detail.save()
											}
											
										}
										
									}
									tr = tr[endKennzeichen+endKennzeichenSearch.size()..-1]
								
								}
							
							}
						
						}
				
				
					}
					
					
					body = body[endRow+endRowSearch.size()..-1]
				
				} else {

					body = ""
					
				}
			
			}
		
		}
	
	}
	
	
	String getDataFromUrl(String url) {
	
		URL oracle = new URL(url);
		URLConnection yc = oracle.openConnection();
		
//		BufferedReader bin = new BufferedReader(new InputStreamReader(yc.getInputStream()));
		BufferedReader bin = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
		
		String inputLine;
		String result = ""
		while ((inputLine = bin.readLine()) != null) {
			result += inputLine
		}
		bin.close();
		return result
	
	}
	
}