package com.gridnine.xtrip.server.tasks

import com.gridnine.xtrip.common.model.dict.Country
import com.gridnine.xtrip.common.model.dict.DictionaryCache
import com.gridnine.xtrip.common.util.TextUtil
import com.gridnine.xtrip.common.util.XmlUtil
import com.gridnine.xtrip.common.xml.DocumentBuilderHelper
import com.gridnine.xtrip.server.storage.DictionaryStorage
import org.w3c.dom.Element

println("===========================")
println("======  Start task  =======")
println("===========================")
Element root
File file = new File("/home/popov/projects/xTrip3-dev/config/xtrip/server/setup/dict/Country.xml")

BufferedInputStream strm = new BufferedInputStream(new FileInputStream(file))
//println("Import the file: " + file.absolutePath)
//println("===========================")

try {
    root = DocumentBuilderHelper.parse(strm).getDocumentElement()
} finally {
    strm.close()
}

def elements = XmlUtil.getElements(root, "object")

List<Country> all = new ArrayList<>(DictionaryCache.get().getAll(Country.class).values())
List<Country> correct = new ArrayList<>()
List<Country> correctXml = new ArrayList<>()
List<Country> xmlRes = new ArrayList<>()
List<Country> notFound = new ArrayList<>()
List<Country> incorrect = new ArrayList<>()

for (Element elm : elements) {
    Country country = new Country()
    country.fromXML(elm)
    xmlRes.add(country)
}

for (Country dictCntr : all) {
    boolean find = false
    for (Country country : xmlRes) {
        if (country.codeVariants.get("IATA") != null
                && dictCntr.codeVariants.get("IATA") != null) {

            if (country.codeVariants.get("IATA")
                    .equals(dictCntr.codeVariants.get("IATA"))){

                correctXml.add(country)
                correct.add(dictCntr)
                find = true
                break
            }
        } else {
            if (country.codeVariants.get("CRT")
                    .equals(dictCntr.codeVariants.get("CRT"))){

                correctXml.add(country)
                correct.add(dictCntr)
                find = true
                break
            }
        }
    }
    if (!find) {
        for (Country country : xmlRes) {
            if (dictCntr?.code == country?.code) {
                incorrect.add(dictCntr)
                find = true
                break
            }
        }
    }
    if (!find) {
        notFound.add(dictCntr)
    }
}

showEquals(all, correct, incorrect, notFound)
setPhoneCode(correctXml)

println("===========================")
println("======= End of task =======")
println("===========================")


def showList(List<Country> list) {
    for (Country ctr : list) {
        StringBuilder result = new StringBuilder()
        result
            .append("|CODE: " + ctr.code + "\t")
            .append("|IATA: " + ctr.codeVariants.get("IATA") + "\t")
            .append("|CRT: " + ctr.codeVariants.get("CRT") + "\t")
            .append("|Name: " + ctr.translations.get(Locale.ENGLISH))

        print(TextUtil.nonBlank(result.toString()) ? result.toString()+"\n" : "")
    }
}

def showEquals(List<Country> all, List<Country> correct, List<Country> incorrect, List<Country> notFound){
    println("Total: " + all.size + ", correct: " + correct.size + ", Incorrect: " + incorrect.size + ", Not found: " + notFound.size)
    if (correct.size > 0){
        println("===========================")
        println("========  Correct  ========")
        showList(correct)
    }
    if (incorrect.size > 0){
        println("===========================")
        println("=======  Incorrect  =======")
        showList(incorrect)
    }
    if (notFound.size > 0){
        println("===========================")
        println("=======  Not found  =======")
        showList(notFound)
    }
}

def setPhoneCode(List<Country> xmlList) {
//    List<Country> phoneCodeIsNull = new ArrayList<>()
//    println("---- Start set phone code ----")
    for (Country country : xmlList) {
        if (TextUtil.isBlank(country.phoneCode)) {
//            phoneCodeIsNull.add(country)
            continue
        }
//        print("Country: " + country + " and phone code: " + country.phoneCode + ", ")
        Country result = DictionaryCache.get().findByCode(Country.class, country.code)
//        println("find: " + result)
        result.setPhoneCode(country.phoneCode)
//        print("set phoneCode: " + result.phoneCode)
        result.setDataSource('AviatranceSetPhoneCodeInCountryDict')
        DictionaryStorage.get().save(result)
//        println(", Save: " + result)
//        println("++++++++++++++++++++++++++++++++++++++++++++")
    }

//    println("----------------------------")
//    println("---- Phone code is null ----")
//    showList(phoneCodeIsNull)

//    println("----------------------------")
//    println("---- End set phone code ----")
}
