//
//  ViewController.swift
//  wifiprint
//
//  Created by woosimsystems on 2021/05/18.
//  Copyright © 2021 Woosim Systems. All rights reserved.
//

import UIKit
import woosim302

class ViewController: UIViewController {

    @IBOutlet weak var rcvDataLabel: UILabel!
    
    var socket: SocketController? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)

       NotificationCenter.default.addObserver(self, selector: #selector(socketDidConnect), name: NSNotification.Name(rawValue: WSSocketDidConnectNotification), object: nil)
       NotificationCenter.default.addObserver(self, selector: #selector(socketDidDisconnect), name: NSNotification.Name(rawValue: WSSocketDidDisconnectNotification), object: nil)
       NotificationCenter.default.addObserver(self, selector: #selector(socketDataReceived), name: NSNotification.Name(rawValue: WSSocketDataReceivedNotification), object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
       
       NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: WSSocketDidConnectNotification), object: nil)
       NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: WSSocketDidDisconnectNotification), object: nil)
       NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: WSSocketDataReceivedNotification), object: nil)
    }

    @objc private func socketDidConnect(notification: NSNotification) {
        guard socket != nil else { return }
        self.navigationItem.rightBarButtonItem?.title = socket?.host
    }
    
    @objc private func socketDidDisconnect(notification: NSNotification) {
        socket = nil
        self.navigationItem.rightBarButtonItem?.title = "Connect"
    }
    
    @objc private func socketDataReceived(notification: NSNotification) {
        guard socket != nil else { return }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            guard self.socket!.readBytesAvailable() > 0 else { return }
            var rcvData = Data()
            while self.socket!.readBytesAvailable() > 0 {
                let data = self.socket!.readData(bytesToRead: self.socket!.readBytesAvailable())
                if data.count > 0 {
                    rcvData.append(data)
                }
            }
            let packet = WSPacket(rcvData)
            if packet.packetType == .MSR {
                let tracks = packet.packetData as! [Data]
                var strData = "MSR Track 1\r\n"
                strData += String(data: tracks[0], encoding: .ascii)!
                strData += "\r\n\nMSR Track 2\r\n"
                strData += String(data: tracks[1], encoding: .ascii)!
                strData += "\r\n\nMSR Track 3\r\n"
                strData += String(data: tracks[2], encoding: .ascii)!
                self.rcvDataLabel.text = strData
            } else {
                self.rcvDataLabel.text = packet.packetData as? String
            }
        }
    }
    
    @IBAction func connectDevice(_ sender: Any) {
        if socket == nil {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            if let connectVC = storyboard.instantiateViewController(withIdentifier: "connectVCID") as? ConnectViewController {
                present(connectVC, animated: true, completion: nil)
            }
        } else {
            let alert = UIAlertController(title: "Close Connection",
                                          message: "Do you want to close connection?",
                                          preferredStyle: UIAlertController.Style.alert)
            let okAction = UIAlertAction(title: "Yes", style: .default, handler: {action in
                self.socket?.disconnect()
            })
            let cancelAction = UIAlertAction(title: "No", style: .default, handler: nil)
            alert.addAction(okAction)
            alert.addAction(cancelAction)
            present(alert, animated: true, completion: nil)
        }
    }
    
    @IBAction func printText(_ sender: Any) {
        let data = NSMutableData()
        data.append(WSCmd.initPrinter())
        data.append(WSCmd.alignText(.Center))
        data.append(WSCmd.extendFont(width: 2, height: 2))
        data.append(Data("Receipt\n".utf8))
        data.append(WSCmd.alignText(.Left))
        data.append(WSCmd.extendFont(width: 1, height: 1))
        data.append(WSCmd.printData())
        data.append(Data("NAME".utf8))
        data.append(WSCmd.alignText(.Right))
        data.append(Data("Woosim Coffee\n".utf8))
        data.append(WSCmd.alignText(.Left))
        data.append(Data("MASTER".utf8))
        data.append(WSCmd.alignText(.Right))
        data.append(Data("Gil-dong Hong\n".utf8))
        data.append(WSCmd.alignText(.Left))
        data.append(Data("ADDRESS".utf8))
        data.append(WSCmd.alignText(.Right))
        data.append(Data("#60, Sandan-ro\n".utf8))
        data.append(Data("388beon-gil, Galsan-myeon\n".utf8))
        data.append(Data("Hongseong-gun, Chungnam-do\n".utf8))
        data.append(Data("Republic of Korea\n".utf8))
        data.append(WSCmd.alignText(.Left))
        data.append(Data("HELP DESK".utf8))
        data.append(WSCmd.alignText(.Right))
        data.append(Data("+82-41-339-3700\n".utf8))
        data.append(WSCmd.alignText(.Left))
        data.append(Data("--------------------------------\n".utf8))
        data.append(Data("Cafe Mocha          2       4.50\n".utf8))
        data.append(Data("Cafe Latte          1       4.00\n".utf8))
        data.append(Data("Cappucino           1       4.00\n".utf8))
        data.append(Data("--------------------------------\n".utf8))
        data.append(Data("Total                     $17.00\n".utf8))
        data.append(WSCmd.printFeed(line: 3))
        socket?.writeData(data as Data)
    }
    
    @IBAction func printImage(_ sender: Any) {
        let data = NSMutableData()
        data.append(WSCmd.initPrinter())
        let logo = UIImage(named: "logo.bmp")!
        data.append(WSImage.printImage(logo, dithering: false, compress: false))
        data.append(WSCmd.printFeed(line: 3))
        socket?.writeData(data as Data)
    }
    
    @IBAction func getDeviceName(_ sender: Any) {
        rcvDataLabel.text = ""
        socket?.writeData(WSCmd.requestDeviceName())
    }
    
    @IBAction func getStatus(_ sender: Any) {
        rcvDataLabel.text = ""
        socket?.writeData(WSCmd.requestStatus())
    }
}

