import com.gridnine.xtrip.common.model.EntityContainer
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.helper.UniqueSettingsRegistry
import com.gridnine.xtrip.common.model.profile.Card
import com.gridnine.xtrip.common.model.profile.OrganizationIndex
import com.gridnine.xtrip.common.model.profile.PCIDSSServerExchangeSettings
import com.gridnine.xtrip.common.model.profile.PersonIndex
import com.gridnine.xtrip.common.search.SearchQuery
import com.gridnine.xtrip.common.search.SearchResult

import java.text.SimpleDateFormat


SearchQuery searchQuery = new SearchQuery()
SearchResult<PersonIndex> searchResultPerson = EntityStorage.get().search(PersonIndex.class, searchQuery)
List<PersonIndex> profiles = searchResultPerson.getData()

EntityContainer<PCIDSSServerExchangeSettings> settings = EntityStorage.get()
        .load(PCIDSSServerExchangeSettings.class,
        UniqueSettingsRegistry.get().getUidByClassName(PCIDSSServerExchangeSettings.class.getName()))


System.out.println("TASK STARTED")
System.out.println("PROFILES: " + profiles.size())
for (PersonIndex profileIndex : profiles) {
    System.out.println("GETTING PROFILE")
    profile = EntityStorage.get().resolve(profileIndex.getSource()).getEntity()
    for (Card card : profile.getCards()) {
        System.out.println("SENDING CARD")
        //HttpURLConnection connection = (HttpURLConnection)(new URL("http://10.0.150.2:8080/card/cards").openConnection())
        HttpURLConnection connection = (HttpURLConnection)(new URL("http://10.0.150.2:8080/card/cards").openConnection())
        connection.setDoInput(true)
        connection.setDoOutput(true)

        SimpleDateFormat formatter = new SimpleDateFormat("MMyy")

        String date
        try {
            date = formatter.format(card.expiration);
        } catch (Exception e) {
            date = "0000"
        }

        String cardDTO = "{ \"profileUID\" : \"" + profile.getUid() + "\", " +
                "\"pan\" : \"" + card.getNumber() + "\", " +
                "\"uid\" : \"" + card.getUid() + "\", " +
                "\"cardholderName\" : \"" + card.getNameOnCard() + "\", " +
                "\"expirationDate\" : \"" + date + "\" }"
        message("Sending card: " + cardDTO)

        connection.addRequestProperty("Cookie", "app-token-3=" + settings.getEntity().getToken())
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST")

        OutputStream outputStream
        try {
            outputStream = connection.getOutputStream()
            OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, "UTF-8")
            streamWriter.write(cardDTO)
            streamWriter.flush()
            System.out.println("RESPONSE: " + connection.getResponseCode())
            message("Response: " + connection.getResponseCode())
        } catch (Exception e) {
            e.printStackTrace()
        }
        finally {
            if (outputStream != null) {
                outputStream.close()
            }
        }
    }
}

searchQuery = new SearchQuery()
SearchResult<OrganizationIndex> searchResultOranization = EntityStorage.get().search(OrganizationIndex.class, searchQuery)
List<OrganizationIndex> organizations = searchResultOranization.getData()


System.out.println("PROFILES: " + profiles.size())
for (OrganizationIndex organizationIndex : organizations) {
    System.out.println("GETTING PROFILE")
    organization = EntityStorage.get().resolve(organizationIndex.getSource()).getEntity()
    for (Card card : organization.getCards()) {
        System.out.println("SENDING CARD")
        //HttpURLConnection connection = (HttpURLConnection)(new URL("http://10.0.150.2:8080/card/cards").openConnection())
        HttpURLConnection connection = (HttpURLConnection)(new URL("http://10.0.150.2:8080/card/cards").openConnection())
        connection.setDoInput(true)
        connection.setDoOutput(true)

        SimpleDateFormat formatter = new SimpleDateFormat("MMyy")

        String date
        try {
            date = formatter.format(card.expiration)
        } catch (Exception e) {
            date = "0000"
        }

        String cardDTO = "{ \"profileUID\" : \"" + organization.getUid() + "\", " +
                "\"pan\" : \"" + card.getNumber() + "\", " +
                "\"uid\" : \"" + card.getUid() + "\", " +
                "\"cardholderName\" : \"" + card.getNameOnCard() + "\", " +
                "\"expirationDate\" : \"" + date + "\" }"
        message("Sending card: " + cardDTO)

        connection.addRequestProperty("Cookie", "app-token-3=" + settings.getEntity().getToken())
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST")

        OutputStream outputStream
        try {
            outputStream = connection.getOutputStream()
            OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, "UTF-8")
            streamWriter.write(cardDTO)
            streamWriter.flush()
            System.out.println("RESPONSE: " + connection.getResponseCode())
            message("Response: " + connection.getResponseCode())
        } catch (Exception e) {
            e.printStackTrace()
        }
        finally {
            if (outputStream != null) {
                outputStream.close()
            }
        }
    }
}

System.out.println("COMPLETED")