//
//  SettingViewController.swift
//  ReverseCalcCalendar
//
//  Created by Itakura on 2019/11/09.
//  Copyright © 2019 Itakura. All rights reserved.
//

import UIKit

class SettingViewController: UIViewController, UITextFieldDelegate, CatchProtocol{

    //アプリ内課金nextButton
    @IBOutlet var nextButton: UIButton!
    
    @IBOutlet weak var dateTextField: UITextField!
    
    @IBOutlet weak var timeTextField: UITextField!
    
    @IBOutlet weak var backgroundView: UIImageView!
    //スクロールビュー
    @IBOutlet var sv: UIScrollView!
    var svUIView = UIView()
    
    //壁紙No
    var selectImageNo: String = ""
    
    //通知関連
    var notificationsColor = [Bool]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        dateTextField.delegate = self
        timeTextField.delegate = self
        
        //キーボードをtimePickerに変更
        timeTextField.inputView = timePicker
        
        //画像の個数
        let imageCount: Int = 13
        //高さ
        let vcHeight:Int = 150
        //画像一つの幅（アスペクト比で幅を計算）
        let imageWidth: Int = vcHeight * 9 / 16
        //座標,幅高さを設定(widthは微調整で+1/2)
        svUIView.frame = CGRect(x: 0, y: 0, width: imageWidth * (imageCount + 1), height: vcHeight)
        
        for i in 0...imageCount - 1 {
            let button:UIButton = UIButton()
            button.tag = i
            //CGFloat型かInt型か統一させる
            button.frame = CGRect(x: imageWidth * i, y: 0, width: imageWidth, height: vcHeight)
            button.imageView?.contentMode = .scaleAspectFill
            
            //画像
            let buttonImage:UIImage = UIImage(named: String(i) + ".jpg")!
            //画像をbuttonにset
            button.setImage(buttonImage, for: .normal)
            //ボタンタップ時の動作
            button.addTarget(self, action: #selector(selectImage), for: .touchUpInside)
            svUIView.addSubview(button)
        }
        
        sv.addSubview(svUIView)
        sv.contentSize = svUIView.bounds.size
        
        
        //キーボードにツールバーを設置
        let toolbar = UIToolbar()
        let flexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let okButton: UIBarButtonItem = UIBarButtonItem(title: "完了",  style: UIBarButtonItem.Style.done, target: self, action: #selector(okButton(_:)))
        okButton.tintColor = UIColor(red: 64/255, green: 157/255, blue: 211/255, alpha: 1)
        //左からflexibleItem、okButtonを設置
        toolbar.setItems([flexibleItem, okButton], animated: true)
        toolbar.sizeToFit()
        timeTextField.inputAccessoryView = toolbar
        dateTextField.inputAccessoryView = toolbar
        
        //textFieldに影を設定
        dateTextField.layer.shadowOffset = CGSize(width: 0, height: 1)
        timeTextField.layer.shadowOffset = CGSize(width: 0, height: 1)
        //影の色
        dateTextField.layer.shadowColor = UIColor.black.cgColor
        timeTextField.layer.shadowColor = UIColor.black.cgColor
        //影の色
        dateTextField.layer.shadowOpacity = 0.2
        timeTextField.layer.shadowOpacity = 0.2
        //影のぼかし
        dateTextField.layer.shadowRadius = 3
        timeTextField.layer.shadowRadius = 3
    }
    override func viewWillAppear(_ animated: Bool) {
        //壁紙設定を反映
        let selectImageNo = UserDefaults.standard.object(forKey: "image")
        if selectImageNo != nil{
            backgroundView.image = UIImage(named: selectImageNo as! String + ".jpg")
        }
        
        //配列にUserDefaultsデータを代入
        notificationsColor = []
        if UserDefaults.standard.object(forKey: "notificationsColor") != nil{
            notificationsColor = UserDefaults.standard.object(forKey: "notificationsColor") as! [Bool]
        }
        print(notificationsColor)
        //「通知対象」をUserDefaultsから反映
        if notificationsColor != []{
            for i in 0...3{
                if notificationsColor[i] == true{
                    self.view.viewWithTag(i + 31)!.isHidden = false
                }else if notificationsColor[i] == false{
                    self.view.viewWithTag(i + 31)!.isHidden = true
                }
            }
        }
        //「予定まで」をUserDefaultsから反映
        if UserDefaults.standard.object(forKey: "notificationsDate") != nil{
            dateTextField.text = (UserDefaults.standard.object(forKey: "notificationsDate") as! String)
        }
        //「通知時間」をUserDefaultsから反映
        if UserDefaults.standard.object(forKey: "notificationsTime") != nil{
            timeTextField.text = (UserDefaults.standard.object(forKey: "notificationsTime") as! String)
        }

        //通知OFFボタン
        if self.view.viewWithTag(31)?.isHidden == false
            || self.view.viewWithTag(32)?.isHidden == false
            || self.view.viewWithTag(33)?.isHidden == false
            || self.view.viewWithTag(34)?.isHidden == false{
            //tag11~14いずれかが表示されている場合はtag15は非表示
            self.view.viewWithTag(35)?.isHidden = true
            timeTextField.textColor = .black
            dateTextField.textColor = .black
        }else{
            //tag11~14全て非表示であればtag15は表示
            self.view.viewWithTag(35)?.isHidden = false
            timeTextField.textColor = .lightGray
            dateTextField.textColor = .lightGray
        }
        
        //アプリ内課金↓＝＝＝＝＝＝＝＝＝＝＝＝＝
        if let buy = UserDefaults.standard.object(forKey: "buy"){//buyがnilでない場合
            let count = UserDefaults.standard.object(forKey: "buy") as! Int
            if count == 1 {
                nextButton.removeFromSuperview()
            }else{
                
            }
            
        }
        //アプリ内課金↑＝＝＝＝＝＝＝＝＝＝＝＝＝
    }
    //キーボードにツールバーを設置
    @objc func okButton(_ sender: UIButton){
        //キーボードを閉じる
        self.view.endEditing(true)
    }
    
    @objc func selectImage(sender:UIButton){
        
        //画像をUIImageViewに反映する
        backgroundView.image = UIImage(named: String(sender.tag) + ".jpg")
        selectImageNo = String(sender.tag)
    }
    //timePicker↓＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
    //UIDatePickerをインスタンス化
    let timePicker: UIDatePicker = {
        let dp = UIDatePicker()
        dp.datePickerMode = UIDatePicker.Mode.time
        dp.timeZone = NSTimeZone.local
        //時間をJapanese(24時間表記)に変更
        dp.locale = Locale.init(identifier: "Japanese")
        dp.addTarget(self, action: #selector(dateChange), for: .valueChanged)
        //最小単位（分）を設定
        dp.minuteInterval = 1
        return dp
    }()
    @objc func dateChange(){
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm"
        timeTextField.text = "\(formatter.string(from: timePicker.date))"
    }
    //timePicker↑＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
    
    //リターンキーを押した時に発動
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //キーボードを閉じる
        textField.resignFirstResponder()
        return true
    }
    //画面タップでキーボードを閉じる
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    
    
    //カラー選択ボタン（複数可）
    @IBAction func whiteButton(_ sender: Any) {
        //自身のオンオフ
        if self.view.viewWithTag(31)!.isHidden{
            //チェックなしの場合
            self.view.viewWithTag(31)?.isHidden = false
        }else{
            self.view.viewWithTag(31)?.isHidden = true
        }
        //通知OFFボタン
        if self.view.viewWithTag(31)?.isHidden == false
            || self.view.viewWithTag(32)?.isHidden == false
            || self.view.viewWithTag(33)?.isHidden == false
            || self.view.viewWithTag(34)?.isHidden == false{
            //tag11~14いずれかが表示されている場合はtag15は非表示
            self.view.viewWithTag(35)?.isHidden = true
            timeTextField.textColor = .black
            dateTextField.textColor = .black
        }else{
            //tag11~14全て非表示であればtag15は表示
            self.view.viewWithTag(35)?.isHidden = false
            timeTextField.textColor = .lightGray
            dateTextField.textColor = .lightGray
        }
    }
    @IBAction func blueButton(_ sender: Any) {
        //自身のオンオフ
        if self.view.viewWithTag(32)!.isHidden{
            //チェックなしの場合
            self.view.viewWithTag(32)?.isHidden = false
        }else{
            self.view.viewWithTag(32)?.isHidden = true
        }
        //通知OFFボタン
        if self.view.viewWithTag(31)?.isHidden == false
            || self.view.viewWithTag(32)?.isHidden == false
            || self.view.viewWithTag(33)?.isHidden == false
            || self.view.viewWithTag(34)?.isHidden == false{
            //tag1~4いずれかが表示されている場合はtag5は非表示
            self.view.viewWithTag(35)?.isHidden = true
            timeTextField.textColor = .black
            dateTextField.textColor = .black
        }else{
            //tag1~4全て非表示であればtag5は表示
            self.view.viewWithTag(35)?.isHidden = false
            timeTextField.textColor = .lightGray
            dateTextField.textColor = .lightGray
        }
    }
    @IBAction func yellowButton(_ sender: Any) {
        //自身のオンオフ
        if self.view.viewWithTag(33)!.isHidden{
            //チェックなしの場合
            self.view.viewWithTag(33)?.isHidden = false
        }else{
            self.view.viewWithTag(33)?.isHidden = true
        }
        //通知OFFボタン
        if self.view.viewWithTag(31)?.isHidden == false
            || self.view.viewWithTag(32)?.isHidden == false
            || self.view.viewWithTag(33)?.isHidden == false
            || self.view.viewWithTag(34)?.isHidden == false{
            //tag1~4いずれかが表示されている場合はtag5は非表示
            self.view.viewWithTag(35)?.isHidden = true
            timeTextField.textColor = .black
            dateTextField.textColor = .black
        }else{
            //tag1~4全て非表示であればtag5は表示
            self.view.viewWithTag(35)?.isHidden = false
            timeTextField.textColor = .lightGray
            dateTextField.textColor = .lightGray
        }
    }
    @IBAction func pinkButton(_ sender: Any) {
        //自身のオンオフ
        if self.view.viewWithTag(34)!.isHidden{
            //チェックなしの場合
            self.view.viewWithTag(34)?.isHidden = false
        }else{
            self.view.viewWithTag(34)?.isHidden = true
        }
        //通知OFFボタン
        if self.view.viewWithTag(31)?.isHidden == false
            || self.view.viewWithTag(32)?.isHidden == false
            || self.view.viewWithTag(33)?.isHidden == false
            || self.view.viewWithTag(34)?.isHidden == false{
            //tag1~4いずれかが表示されている場合はtag5は非表示
            self.view.viewWithTag(35)?.isHidden = true
            timeTextField.textColor = .black
            dateTextField.textColor = .black
        }else{
            //tag1~4全て非表示であればtag5は表示
            self.view.viewWithTag(35)?.isHidden = false
            timeTextField.textColor = .lightGray
            dateTextField.textColor = .lightGray
        }
    }
    
    @IBAction func offButton(_ sender: Any) {
        if self.view.viewWithTag(35)!.isHidden{
            //自身をオン
            self.view.viewWithTag(35)?.isHidden = false
            self.view.viewWithTag(31)?.isHidden = true
            self.view.viewWithTag(32)?.isHidden = true
            self.view.viewWithTag(33)?.isHidden = true
            self.view.viewWithTag(34)?.isHidden = true
            timeTextField.textColor = .lightGray
            dateTextField.textColor = .lightGray
        }else{
            //自身をオフ
            self.view.viewWithTag(35)?.isHidden = true
            self.view.viewWithTag(31)?.isHidden = false
            self.view.viewWithTag(32)?.isHidden = false
            self.view.viewWithTag(33)?.isHidden = false
            self.view.viewWithTag(34)?.isHidden = false
            timeTextField.textColor = .black
            dateTextField.textColor = .black
        }
    }
    @IBAction func save(_ sender: Any) {
        //壁紙画像反映：Buttonのtag情報をアプリ内へ保存する
        if selectImageNo != ""{
            UserDefaults.standard.set(selectImageNo, forKey: "image")
        }
        
        //通知設定反映
        notificationsColor = []
        for i in 31...34{
            if self.view.viewWithTag(i)!.isHidden{
                notificationsColor.append(false)
            }else{
                notificationsColor.append(true)
            }
        }
        //通知対象Colorを保存
        UserDefaults.standard.set(notificationsColor, forKey: "notificationsColor")
        //通知Dateを保存
        if dateTextField != nil{
            UserDefaults.standard.set(dateTextField.text, forKey: "notificationsDate")
        }
        //通知timeを保存
        if timeTextField != nil{
            UserDefaults.standard.set(timeTextField.text, forKey: "notificationsTime")
        }
        
        //前画面に戻る
        self.navigationController?.popViewController(animated: true)
    }
    
    
    //アプリ内課金↓＝＝＝＝＝＝＝＝＝＝＝＝＝
    func catchData(count: Int) {
        if count == 1 {
            //nextボタンを非表示にする
            nextButton.removeFromSuperview()
        }
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let adRemoveVC = segue.destination as! AdRemoveViewController
        adRemoveVC.delegate = self
    }
    
    @IBAction func next(_ sender: Any) {
        performSegue(withIdentifier: "next", sender: nil)
    }
    //アプリ内課金↑＝＝＝＝＝＝＝＝＝＝＝＝＝
    
}
