//
//  LKFMainViewController.swift
//  LKF
//
//  Created by Alexander Holzer on 06.06.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Cocoa
import lkfcm

class LKFMainViewController: NSViewController {

    @IBOutlet weak var labelInfo: NSTextField!
    @IBOutlet weak var txtRootPath: NSTextField!
    @IBOutlet weak var txtFileName: NSTextField!
    @IBOutlet weak var comboPeriod: NSComboBox!
    @IBOutlet weak var comboModel: NSComboBox!
    @IBOutlet weak var txtOutputPath: NSTextField!
    @IBOutlet weak var chkTestOutput: NSButton!
    @IBOutlet weak var txtFlags: NSTextField!
    
    @IBOutlet weak var labelResult: NSTextFieldCell!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        labelResult.stringValue = "Click Run."
        comboModel.selectItem(at: 1)
        comboPeriod.selectItem(at: 1)
    }
    
    @IBAction func comboPeriodChanged(_ sender: Any) {
        comboModel.selectItem(at: comboPeriod.indexOfSelectedItem)
    }
    
    @IBAction func browseFileClicked(_ sender: Any) {
        let dialog = NSOpenPanel();
        dialog.title                   = "Input-File auswählen";
        dialog.showsResizeIndicator    = true;
        dialog.showsHiddenFiles        = false;
        dialog.canChooseDirectories    = false;
        dialog.canCreateDirectories    = true;
        dialog.allowsMultipleSelection = false;
        //dialog.allowedFileTypes        = ["txt"];
            
        if (dialog.runModal() == NSApplication.ModalResponse.OK) {
            let result = dialog.url // Pathname of the file
                
            if (result != nil) {
                txtFileName.stringValue = result!.path
            }
        } else {
            // User clicked on "Cancel"
            return
        }
    }
    
    
    @IBAction func browseDataPathClicked(_ sender: Any) {
        let dialog = NSOpenPanel();
        dialog.title                   = "Stammdaten-Pfad auswählen";
        dialog.showsResizeIndicator    = true;
        dialog.showsHiddenFiles        = false;
        dialog.canChooseDirectories    = true;
        dialog.canChooseFiles = false
        dialog.canCreateDirectories    = true;
        dialog.allowsMultipleSelection = false;
        //dialog.allowedFileTypes        = ["txt"];
        
        if (dialog.runModal() == NSApplication.ModalResponse.OK) {
            let result = dialog.url // Pathname of the file
            
            if (result != nil) {
                txtRootPath.stringValue = result!.path
            }
        } else {
            // User clicked on "Cancel"
            return
        }
    }
    
    @IBAction func errorlistClicked(_ sender: Any) {

        if let model = UInt32(comboModel.stringValue) {
            let context: LKFContext
            do {
                context = try LKFContext(model: model, path: txtRootPath.stringValue)
                
                if context.lastError != nil {
                    labelResult.stringValue = context.lastError!.message
                    return
                }
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }
            
            let outputUrl = URL(fileURLWithPath: txtOutputPath.stringValue, isDirectory: true)
            
            let errorlistFile = LKFOutputErrorlistFile(context:context)
            var outputFile = outputUrl.appendingPathComponent(errorlistFile.defaultfileName, isDirectory: false)
            do {
                try context.write(output:errorlistFile, file: outputFile)
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }
            labelResult.stringValue = "\(outputFile.absoluteString) written"

            let satzartFile = LKFOutputRowDescriptionFile (context:context)
            outputFile = outputUrl.appendingPathComponent(satzartFile.defaultfileName, isDirectory: false)
            do {
                try context.write(output:satzartFile, file: outputFile)
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }
            labelResult.stringValue = "\(outputFile.absoluteString) written"

        }
    }
    
    @IBAction func browseOutputPathClicked(_ sender: Any) {
        let dialog = NSOpenPanel();
        dialog.title                   = "Output-Pfad auswählen";
        dialog.showsResizeIndicator    = true;
        dialog.showsHiddenFiles        = false;
        dialog.canChooseDirectories    = true;
        dialog.canChooseFiles = false
        dialog.canCreateDirectories    = true;
        dialog.allowsMultipleSelection = false;
        //dialog.allowedFileTypes        = ["txt"];
        
        if (dialog.runModal() == NSApplication.ModalResponse.OK) {
            let result = dialog.url // Pathname of the file
            
            if (result != nil) {
                txtOutputPath.stringValue = result!.path
            }
        } else {
            // User clicked on "Cancel"
            return
        }
    }
    
    @IBAction func runClicked(_ sender: Any) {
        
        if let model = UInt32(comboModel.stringValue) {
            let computationYear = Int32(comboPeriod.stringValue) ?? Int32(model)
        
            let context: LKFContext
            do {
                context = try LKFContext(model: model, path: txtRootPath.stringValue)
                
                if context.lastError != nil {
                    labelResult.stringValue = context.lastError!.message
                    return
                }
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }
            
            context.setContextParameters(year:computationYear)
            let fileUrl = URL(fileURLWithPath: txtFileName.stringValue, isDirectory:false)
        
            if let flags = Int32(txtFlags.stringValue) {
                context.flags = flags
            }
            
            if chkTestOutput.state == NSControl.StateValue.on {
                context.createOutputForTest = true
            }
            
            do {
                try context.load (file: fileUrl, encoding: .ascii, enableComparing: false)
            }
            catch {
                labelResult.stringValue = error.localizedDescription 
                return
            }
            

            
            let outputUrl = URL(fileURLWithPath: txtOutputPath.stringValue, isDirectory: true)
            do {
                try context.execute()
                try context.writeData(path:outputUrl)
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }
            labelResult.stringValue = "data written to \(outputUrl.absoluteString)."
            let errorFile = LKFOutputErrorFile(context:context)
            var outputFile = outputUrl.appendingPathComponent(errorFile.defaultfileName, isDirectory: false)
            do {
                 try context.write(output:errorFile, file: outputFile)
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }
            
            let warningFile = LKFOutputWarningFile(context:context)
            outputFile = outputUrl.appendingPathComponent(warningFile.defaultfileName, isDirectory: false)
            do {
                 try context.write(output:warningFile, file: outputFile)
            }
            catch {
                labelResult.stringValue = error.localizedDescription
                return
            }

            
            labelResult.stringValue = "\(outputFile.absoluteString) written"
        } else {
            labelResult.stringValue = "cannot execute action"
        }
    }
}
