//
//  OfferFormViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 29.05.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class OfferFormViewController: ViewControllerWithMenu, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var titleContentView: UIView!
    private static let titleCellIdentifier = "titleCell"
    private static let fieldCellIdentifier = "fieldCell"
    private static let linkCellIdentifier = "linkCell"
    //  pointType: [city, village]
    var pointTypes = ["city", "village"]
    var listTypeForParam = "sw_cities_table"
    var pointType = "city" {
        didSet {
            self.cells = cellsForPointType(pointType)
            clearForItem("point_type")
            requestTargetingList("point_type")
        }
    }
    var rememberedItems = false
    var cityId:String? {
        didSet {
            guard cityId != nil else { return }
            clearForItem("your_city")
            requestTargetingList("your_city")
        }
    }
    var regionId: String? {
        didSet  {
            guard regionId != nil else { return }
            clearForItem("region")
            requestTargetingList("region")
        }
    }
    var areaId:String? {
        didSet {
            guard areaId != nil else { return }
            clearForItem("area")
            requestTargetingList("area")
        }
    }
    var villageId: String? {
        didSet {
            guard villageId != nil else { return }
            clearForItem("village")
            requestTargetingList("village")
        }
    }
    var streetId:String? {
        didSet {
            guard streetId != nil else { return }
            clearForItem("street")
            requestTargetingList("street")
        }
    }
    var houseId:String? {
        didSet {
            guard houseId != nil else { return }
            tableView.reloadData()
        }
    }
    let defaultTypes = ["your_city", "region", "area", "village", "street", "house"]
    var currentPayType: String = ""
    @IBOutlet weak var tableView: UITableView!
    let reuseCellIdentifier = "cell"
    var cells:[[String]] = [[OfferFormViewController.titleCellIdentifier, "turn_on_selected_service"],
                            [OfferFormViewController.fieldCellIdentifier, "point_type"],
                            [OfferFormViewController.fieldCellIdentifier, "your_city"],
                            [OfferFormViewController.fieldCellIdentifier, "area"],
                            [OfferFormViewController.fieldCellIdentifier, "street"],
                            [OfferFormViewController.fieldCellIdentifier, "house"],
                            [OfferFormViewController.linkCellIdentifier, "check"]]
    var cities: [[String]] = [] {
        didSet {
            OffersManager.sharedInstance().cities = cities
        }
    }
    var areas: [[String]] = [] {
        didSet {
            OffersManager.sharedInstance().areas = areas
        }
    }
    var streets: [[String]] = [] {
        didSet {
            OffersManager.sharedInstance().streets = streets
        }
    }
    var houses: [[String]] = [] {
        didSet {
            OffersManager.sharedInstance().houses = houses
        }
    }
    var villages: [[String]] = [] {
        didSet {
            OffersManager.sharedInstance().villages = villages
        }
    }
    var regions: [[String]] = [] {
        didSet {
            OffersManager.sharedInstance().regions = regions
        }
    }
    
    func cellsForPointType(title: String) -> [[String]] {
        if title == "city" {
            return [[OfferFormViewController.titleCellIdentifier, "turn_on_selected_service"],
                    [OfferFormViewController.fieldCellIdentifier, "point_type"],
                    [OfferFormViewController.fieldCellIdentifier, "your_city"],
                    [OfferFormViewController.fieldCellIdentifier, "area"],
                    [OfferFormViewController.fieldCellIdentifier, "street"],
                    [OfferFormViewController.fieldCellIdentifier, "house"],
                    [OfferFormViewController.linkCellIdentifier, "check"]]
        } else {
            return [[OfferFormViewController.titleCellIdentifier, "turn_on_selected_service"],
                    [OfferFormViewController.fieldCellIdentifier, "point_type"],
                    [OfferFormViewController.fieldCellIdentifier, "region"],
                    [OfferFormViewController.fieldCellIdentifier, "area"],
                    [OfferFormViewController.fieldCellIdentifier, "village"],
                    [OfferFormViewController.fieldCellIdentifier, "street"],
                    [OfferFormViewController.fieldCellIdentifier, "house"],
                    [OfferFormViewController.linkCellIdentifier, "check"]]
        }
    }
    
    func clearItems(titles: [String]) {
        for title in titles {
            switch title {
            case "your_city":
                cities = []
                cityId = nil
                break
            case "region":
                regions = []
                regionId = nil
                break
            case "area":
                areas = []
                areaId = nil
                break
            case "village":
                villages = []
                villageId = nil
                break
            case "street":
                streets = []
                streetId = nil
                break
            case "house":
                houses = []
                houseId = nil
                break
            default: break
            }
        }
    }
    
    func clearForItem(title: String) {
        switch title {
        case "point_type":
            clearItems(["your_city", "region", "area", "village", "street", "house"])
        case "your_city":
            clearItems(["region", "area", "village", "street", "house"])
        case "region":
            clearItems(["your_city", "area", "village", "street", "house"])
        case "area":
            clearItems(["village", "street", "house"])
        case "village":
            clearItems(["street", "house"])
        case "street":
            clearItems(["house"])
        default:
            break
        }
    }
    
    func offsetItem(title:String) -> String {
        switch (pointType, title) {
        case ("city", "point_type"):
            return "your_city"
        case ("city", "your_city"):
            return "area"
        case ("city", "area"):
            return "street"
        case ("city", "street"):
            return "house"
        case ("village", "point_type"):
            return "region"
        case ("village", "region"):
            return "area"
        case ("village", "area"):
            return "village"
        case ("village", "village"):
            return "street"
        case ("village", "street"):
            return "house"
        default:
            return ""
        }
    }
    
    func generateRequestByItem(title: String) -> GetTargetingListRequest? {
        var request: GetTargetingListRequest?
        switch (pointType, title) {
        case ("city", "your_city"), ("village", "region"):
            request = GetTargetingListRequest(listType: listTypeForParam)
            break
        case ("city", "area"):
            request = GetTargetingListRequest(listType: listTypeForParam, cityId: cityId)
            break
        case ("city", "street"):
            request = GetTargetingListRequest(listType: listTypeForParam, cityId: cityId, areaId: areaId)
        case ("city", "house"):
            request = GetTargetingListRequest(listType: listTypeForParam, cityId: cityId, areaId: areaId, streetId: streetId)
        case ("village", "area"):
            request = GetTargetingListRequest(listType: listTypeForParam, regionId: regionId)
        case ("village", "village"):
            request = GetTargetingListRequest(listType: listTypeForParam, regionId: regionId, areaId: areaId)
        case ("village", "street"):
            request = GetTargetingListRequest(listType: listTypeForParam, regionId: regionId, villageId: villageId, areaId: areaId)
            break
        case ("village", "house"):
            request = GetTargetingListRequest(listType: listTypeForParam, regionId: regionId, villageId: villageId, areaId: areaId, streetId: streetId)
            break
        default:
            break
        }
        return request
    }
    
    func requestTargetingList(title: String) {
        let currentItem = offsetItem(title)
        setListTypeForItem(currentItem)
        let request = generateRequestByItem(currentItem)
        if let request = request {
            Facade.sharedInstance().getTargetingList(request.params, onSuccess: { (dict) in
                switch (self.pointType, currentItem) {
                case ("city", "your_city"):
                    self.cities = dict
                    break
                case (_, "area"):
                    self.areas = dict
                    break
                case (_, "street"):
                    self.streets = dict
                    break
                case (_, "house"):
                    self.houses = dict
                    break
                case ("village", "region"):
                    self.regions = dict
                    break
                case ("village", "village"):
                    self.villages = dict
                    break
                default:
                    break
                }
                self.tableView.reloadData()
                }, onError: { (error) in
                    
                }, onFinish: {
                    
            })
        }
    }
    
    func setListTypeForItem(title: String) {
        switch (pointType, title) {
        case ("city", "your_city"):
            listTypeForParam = "sw_cities_table"
            break
        case ("city", "area"):
            listTypeForParam = "sw_areas_table"
            break
        case ("city", "street"):
            listTypeForParam = "sw_streets_table"
        case ("city", "house"):
            listTypeForParam = "sw_addresses_table"
        case ("village", "region"):
            listTypeForParam = "sp_regions"
            break
        case ("village", "area"):
            listTypeForParam = "sp_areas"
        case ("village", "village"):
            listTypeForParam = "sp_villages"
        case ("village", "street"):
            listTypeForParam = "sp_streets"
            break
        case ("village", "house"):
            listTypeForParam = "sp_addresses"
            break
        default:
            break
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localize()
        configureBlueNavbar()
//        addBackButtonForDefault(.whiteColor())
        self.navigationItem.title = "Предложения для вас"
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.pointType = self.pointTypes[0]
        configureTableView()
        fillFieldsWithRememberedValues()
    }
    
    func fillFieldsWithRememberedValues() {
        if let pointTypeFromcache = OffersManager.sharedInstance().pointType {
            self.rememberedItems = true
            self.pointType = pointTypeFromcache
            self.cityId = OffersManager.sharedInstance().cityId
            self.regionId = OffersManager.sharedInstance().regionId
            self.areaId = OffersManager.sharedInstance().areaId
            self.villageId = OffersManager.sharedInstance().villageId
            self.streetId = OffersManager.sharedInstance().streetId
            self.houseId = OffersManager.sharedInstance().houseId
            if let cities = OffersManager.sharedInstance().cities {
                self.cities = cities
            }
            if let areas = OffersManager.sharedInstance().areas {
                self.areas = areas
            }
            if let streets = OffersManager.sharedInstance().streets {
                self.streets = streets
            }
            if let houses = OffersManager.sharedInstance().houses {
                self.houses = houses
            }
            if let villages = OffersManager.sharedInstance().villages {
                self.villages = villages
            }
            if let regions = OffersManager.sharedInstance().regions {
                self.regions = regions
            }
            self.tableView.reloadData()
        }
    }
    
//    // MARK: Keyboard action
//    override func keyboardDidShow(notification: NSNotification) {
//        tapGestureRecognizer.enabled = true
//        let info = notification.userInfo!
//        var kbRect = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
//        kbRect = view.convertRect(kbRect, fromView: nil)
//        
//        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0,
//                                         bottom:	kbRect.height, right: 0.0)
//        tableView.contentInset = contentInsets
//        tableView.scrollIndicatorInsets = contentInsets
//        let aRect = view.frame
//        if let textField = activeField	where !CGRectContainsPoint(aRect, textField.frame.origin) {
//            tableView.scrollRectToVisible(textField.frame, animated: true)
//        }
//    }
    
//    override func keyboardWillBeHidden(notification: NSNotification) {
//        tapGestureRecognizer.enabled = false
//        let contentInsets = UIEdgeInsetsZero
//        tableView.contentInset = contentInsets
//        tableView.scrollIndicatorInsets = contentInsets
//        resizeScrollViewToFitSubviews()
//    }
    
//    override func resizeScrollViewToFitSubviews() {
//        tableView.reloadData()
//    }
    
    private func configureTableView() {
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "payment_form" {
            let vc = segue.destinationViewController as! OnlinePaymentFormViewController
            vc.data = sender as? NSData
        } else if segue.identifier == "showOfferModal" {
            //      let navVC = segue.destinationViewController as! UINavigationController
            //      let vc = navVC.topViewController as! OffersSelectListViewController
            let vc = segue.destinationViewController as! OffersSelectListViewController
            let title = sender as! String
            vc.vc = self
            vc.items = itemsByType(title)
            vc.type = title
            let key = "offer_form.label.\(title)"
            vc.title = LocalizedString(key)
            
        } else if segue.identifier == "showOffers" {
            let vc = segue.destinationViewController as! OffersViewController
            vc.specialOffers = sender as! [SpecialOffer]
        }
    }
    
    func itemsByType(title: String) -> [[String]] {
        var items:[[String]] = []
        switch title {
        case "point_type":
            items = [["1", pointTypes[0]], ["2", pointTypes[1]]]
            break
        case "your_city":
            for item in cities {
                items.append(item)
            }
            break
        case "region":
            for item in regions {
                items.append(item)
            }
            break
        case "area":
            for item in areas {
                items.append(item)
            }
            break
        case "village":
            for item in villages {
                items.append(item)
            }
            break
        case "street":
            for item in streets {
                items.append(item)
            }
            break
        case "house":
            for item in houses {
                items.append(item)
            }
            break
        default: break
        }
        return items
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        if isBeingDismissed() || isMovingFromParentViewController() {
            clearFields()
        }
    }
    
    private func clearFields() {
        pointType = "city"
        cityId = nil
        areaId = nil
        streetId = nil
        houseId = nil
    }
    
}

// UITableViewDelegate
extension OfferFormViewController {
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch cells[indexPath.row][0] {
        case OfferFormViewController.fieldCellIdentifier:
            let fieldCell = tableView.cellForRowAtIndexPath(indexPath) as! OfferFormFieldCell
            fieldCell.customCellSelected(self, title: cells[indexPath.row][1])
            break
        default: break
        }
    }
}

// UITableViewDataSource
extension OfferFormViewController {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cells.count
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        (cell as? OfferFormFieldCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        switch cells[indexPath.row][0] {
        case OfferFormViewController.titleCellIdentifier:
            let titleCell = tableView.dequeueReusableCellWithIdentifier(OfferFormViewController.titleCellIdentifier, forIndexPath: indexPath) as! OfferFormTitleCell
            cell = titleCell
            break
        case OfferFormViewController.fieldCellIdentifier:
            let fieldCell = tableView.dequeueReusableCellWithIdentifier(OfferFormViewController.fieldCellIdentifier, forIndexPath: indexPath) as! OfferFormFieldCell
            fieldCell.fillCell(cells[indexPath.row][1], vc: self)
            cell = fieldCell
            break
        case OfferFormViewController.linkCellIdentifier:
            let linkCell = tableView.dequeueReusableCellWithIdentifier(OfferFormViewController.linkCellIdentifier, forIndexPath: indexPath) as! OfferFormLinkCell
            linkCell.fillCell(self)
            cell = linkCell
            break
        default: break
        }
        //cell.selectionStyle = .None
        return cell
    }
    
}

//extension OfferFormViewController {
//    override func textFieldDidBeginEditing(textField: UITextField) {
//        let cell: UITableViewCell?
//        
//        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
//            // Load resources for iOS 6.1 or earlier
//            cell = textField.superview?.superview as? UITableViewCell
//            
//        } else {
//            // Load resources for iOS 7 or later
//            cell = textField.superview?.superview?.superview as? UITableViewCell
//            // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
//        }
//        if let cell = cell {
//            if let indexPath = tableView.indexPathForCell(cell) {
//                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
//            }
//        }
//    }
//    
//    override func textFieldDidEndEditing(textField: UITextField) {
//        activeField = nil
//    }
//    
//}

extension OfferFormViewController {
    override var localizedId: String {
        return "offer_form"
    }
}
