import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.EntityReference
import com.gridnine.xtrip.common.model.booking.OperationBatch
import com.gridnine.xtrip.common.model.dict.AddressType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.helpers.DictHelper
import com.gridnine.xtrip.common.model.helpers.ProfileHelper
import com.gridnine.xtrip.common.model.profile.Address
import com.gridnine.xtrip.common.model.profile.Organization
import com.gridnine.xtrip.common.model.system.ContentType
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicketType
import org.apache.poi.ss.usermodel.Workbook

import java.text.SimpleDateFormat

createStyle(name: "left", h_alignment: "LEFT", fontFamily: "TimesNewRoman", fontHeight: 10)
createStyle(name: "left-bold", h_alignment: "LEFT", fontBold: true, fontFamily: "TimesNewRoman", fontHeight: 10)
createStyle(name: "left-border", h_alignment: "LEFT", topBorder: 'THIN', rightBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', wrapText: true, fontFamily: "TimesNewRoman", fontHeight: 10)
createStyle(name: "left-bold-border", h_alignment: "LEFT", fontBold: true, topBorder: 'THIN', rightBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', wrapText: true, fontFamily: "TimesNewRoman", fontHeight: 10)
createStyle(name: "center-border", h_alignment: "CENTER", topBorder: 'THIN', rightBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', wrapText: true, fontFamily: "TimesNewRoman", fontHeight: 10)


def fillSheet() {
    addPicture()
    fillHeader()
    fillTable()
    fillSignature()
}

def addPicture() {
    Organization supplier = (Organization) EntityStorage.get().resolve(parameters['key-report-params']?.supplier)?.getEntity()
    if (supplier && supplier.getLogo() && supplier.getLogo().getData()) {
        int pictureType = supplier.getLogo().getContentType() == ContentType.PNG ?
                Workbook.PICTURE_TYPE_PNG : supplier.getLogo().getContentType() == ContentType.JPEG ?
                Workbook.PICTURE_TYPE_JPEG : -1
        if (pictureType >= 0) {
            picture(1, 1, 7, 10, supplier.getLogo().getData(), pictureType, 1, 1.1)
        }
    }
}

def fillHeader() {
    rowHeight(14)
    nextColumn()
    fillLeftCell("\"Approved\"")
    3.times {
        nextColumn()
    }
    fillLeftCell("Attachment 1")
    nextRow()
    nextColumn()
    Organization supplier = (Organization) EntityStorage.get().resolve(parameters['key-report-params']?.supplier)?.getEntity()
    text("VP Finance, ".concat(ProfileHelper.getFullName(supplier.getCode(), supplier.getShortName(), supplier.getFullName(), supplier.getLegalForm(), LocaleHelper.EN_LOCALE, false, false)), "left", 1, 1)
    nextRow()
    nextColumn()
    fillLeftCell("__________________________")
    2.times {
        nextRow()
    }
    nextColumn()
    fillLeftCell(new SimpleDateFormat("\"dd\" MMMM yyyy", LocaleHelper.EN_LOCALE).format(new Date()))
    4.times {
        nextRow()
    }
    2.times {
        nextColumn()
    }
    fillBoldLeftCell("MONTH END STOCK REPORT")
    3.times {
        nextRow()
    }
    EntityReference<Organization> agency = parameters['key-report-params']?.agency
    String name = "Name of Agent: "
    String iata = "IATA Code: "
    String location = ""
    if (agency) {
        Organization organization = EntityStorage.get().resolve(agency)?.getEntity()
        if (organization) {
            name = name.concat(ProfileHelper.getFullName(
                    organization, LocaleHelper.EN_LOCALE, false))
            //TODO get IATA code from profile after IBECORP-6061
            Address address = organization.getAddresses().find { a ->
                a.getAddressType() == AddressType.LEGAL
            }
            if (address) {
                String city = address.getCity() ? DictHelper.getTranslation(address.getCity(), LocaleHelper.EN_LOCALE, false) : ""
                String street = address.getHouse() ?
                        address.getAddress() ?
                                address.getAddress().toString(LocaleHelper.EN_LOCALE).concat(" ")
                                        .concat(address.getHouse().toString(LocaleHelper.EN_LOCALE)) :
                                "" :
                        address.getAddress() ?
                                address.getAddress().toString(LocaleHelper.EN_LOCALE) :
                                address.getHouse().toString(LocaleHelper.EN_LOCALE)
                location = city.concat(", ").concat(street)
            }
        }
    }
    nextColumn()
    fillLeftCell(name)
    nextColumn()
    fillLeftCell("Location:")
    fillLeftCell(location)
    nextRow()
    nextColumn()
    fillLeftCell(iata)
    nextColumn()
    fillLeftCell("Period:")
    SimpleDateFormat sdfPeriod = new SimpleDateFormat("ddMMM", LocaleHelper.EN_LOCALE)
    Date fromDate = parameters['key-report-params']?.periodBegin
    String from = fromDate ? sdfPeriod.format(fromDate).toUpperCase() : ""
    Date toDate = parameters['key-report-params']?.periodEnd
    String to = toDate ? sdfPeriod.format(toDate).toUpperCase() : ""
    fillLeftCell(String.format("%s-%s", from, to))
    nextRow()
    3.times {
        nextColumn()
    }
    fillLeftCell("Date:")
    fillLeftCell(new SimpleDateFormat("M/d/yyyy").format(new Date()))
    2.times {
        nextRow()
    }
}

def fillTable() {
    fillTableHeader()
    fillTableBody()
}

def fillSignature() {
    nextColumn()
    fillLeftCell("Signature of Agent    ______________________________")
    2.times {
        nextRow()
    }
    nextColumn()
    fillLeftCell("Validation Stamp")
}

def fillTableHeader() {
    nextColumn()
    fillBoldLeftBorderCell("")
    fillBoldLeftBorderCell("Document type")
    fillBoldLeftBorderCell("First Serial №")
    fillBoldLeftBorderCell("Last Serial №")
    fillBoldLeftBorderCell("Quantity")
    nextRow()
}

def fillTableBody() {
    String firstSerial = ""
    String lastSerial = ""
    int quantity = 0
    Date minDate
    Date maxDate
    tickets { AirTicketsTemplateReportTicket ticket ->
        if (ticket.getType() == AirTicketsTemplateReportTicketType.PRODUCT && ticket.getOperationBatch() != OperationBatch.REFUND) {
            if (minDate == null && maxDate == null) {
                minDate = ticket.getIssueDate()
                maxDate = ticket.getIssueDate()
                firstSerial = String.format("%s-%s", ticket.getCarrierNumber(), ticket.getTicketNumber())
                lastSerial = String.format("%s-%s", ticket.getCarrierNumber(), ticket.getTicketNumber())
            } else if (minDate.after(ticket.getIssueDate())) {
                firstSerial = String.format("%s-%s", ticket.getCarrierNumber(), ticket.getTicketNumber())
            } else if (maxDate.before(ticket.getIssueDate())) {
                lastSerial = String.format("%s-%s", ticket.getCarrierNumber(), ticket.getTicketNumber())
            }
            quantity++
        }
    }
    fillBlock("Remaining stock (at the beginning of period)",
            "Total remaining stock (at the beginning of period)")
    fillBlock("Receiving stock", "Total receiving stock")
    fillBlock("Issued stock", "Total issued stock",
            firstSerial, lastSerial, String.valueOf(quantity))
    fillBlock("Returned stock", "Total returned stock")
    fillBlock("Remaining stock at the end of period",
            "Total remaining stock (at the end of period)", "Void")
    nextRow()
}

def fillBlock(String name, String total) {
    fillBlock(name, total, true)
}

def fillBlock(String name, String total, boolean emptyRow) {
    fillBlock(name, total, emptyRow, "", "", "", "")
}

def fillBlock(String name, String total, String abyss) {
    fillBlock(name, total, false, abyss, "", "", "")
}

def fillBlock(String name, String total, String firstSerial,
              String lastSerial, String quantity) {
    fillBlock(name, total, true, "", firstSerial, lastSerial, quantity)
}

def fillBlock(String name, String total, boolean emptyRow, String abyss,
              String firstSerial, String lastSerial, String quantity) {
    nextColumn()
    fillLeftBorderCell(name)
    fillLeftBorderCell(abyss)
    3.times {
        fillLeftBorderCell("")
    }
    nextRow()
    nextColumn()
    fillLeftBorderCell("")
    fillLeftBorderCell("Tickets")
    fillCenterBorderCell(firstSerial)
    fillCenterBorderCell(lastSerial)
    fillCenterBorderCell(quantity)
    nextRow()
    nextColumn()
    fillLeftBorderCell("")
    fillLeftBorderCell("Excess Baggage Tickets")
    3.times {
        fillLeftBorderCell("")
    }
    nextRow()
    nextColumn()
    fillLeftBorderCell("")
    fillLeftBorderCell("MCOs")
    3.times {
        fillLeftBorderCell("")
    }
    nextRow()
    nextColumn()
    fillBoldLeftBorderCell(total)
    4.times {
        fillLeftBorderCell("")
    }
    nextRow()
    if (emptyRow) {
        fillEmptyRow()
    }
}

def fillEmptyRow() {
    nextColumn()
    5.times {
        fillLeftBorderCell("")
    }
    nextRow()
}

def fillLeftCell(String data) {
    fillCell(data, "left")
}

def fillBoldLeftCell(String data) {
    fillCell(data, "left-bold")
}

def fillLeftBorderCell(String data) {
    fillCell(data, "left-border")
}

def fillBoldLeftBorderCell(String data) {
    fillCell(data, "left-bold-border")
}

def fillCenterBorderCell(String data) {
    fillCell(data, "center-border")
}

def fillCell(String data, String style) {
    text(data, style, 1, 1)
    nextColumn()
}

def setWidth() {
    nextRow()
    columnWidth(3)
    nextColumn()
    columnWidth(41)
    nextColumn()
    columnWidth(27)
    nextColumn()
    columnWidth(17)
    nextColumn()
    columnWidth(17)
    nextColumn()
    columnWidth(9)
}

page { "STOCK" } {
    // Set fix width for amount of sheets
    fitWidth(1)

    // Set fix height for amount of sheets
    fitHeight(1)

    // Set portrait mode
    landscape(false)

    // Set narrow margins
    margin(0.25, 0.25, 0.25, 0.25)

    // Set scale
    scale(70)

    // Set preserve mode
    preserve(true)

    fillSheet()
    setWidth()
}
