//
//  StoreProductListView.swift
//  NearbyStores
//
//  Created by Amine on 7/4/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit

protocol StoreReviewDelegate {
    func onPress(object: Review)
    func onLoaded(list: [Review])
    func loadMore(view: StoreReviewListView)
}

class StoreReviewListView: UIView {
    
    var delegate: StoreReviewDelegate? = nil
     var list:[Review] = []
    
    var calculatedHeight = CGFloat(0)
    
    func addItemLoadMore(action: @escaping () -> ()) {
        
        let viewMoreBtn = UIButton(
            frame: CGRect(x: 0, y: calculatedHeight, width: self.frame.width, height: 40)
        )
        
        
        self.addSubview(viewMoreBtn)
        
        viewMoreBtn.setTitle( "Show More Reviews".localized, for: .normal)
        viewMoreBtn.setTitleColor(Colors.primaryColor, for: .normal)
        viewMoreBtn.useFontRegular()
        viewMoreBtn.backgroundColor = UIColor.white
        
        let underLineAttributes : [NSAttributedString.Key: Any] = [
            NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14),
            NSAttributedString.Key.foregroundColor : Colors.primaryColor,
            NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single.rawValue]
        
        if let str = viewMoreBtn.titleLabel?.text {
            let attributeString = NSMutableAttributedString(string: str,
                                                            attributes: underLineAttributes)
            viewMoreBtn.setAttributedTitle(attributeString, for: .normal)
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + deadline) {
            
            viewMoreBtn.translatesAutoresizingMaskIntoConstraints = false
            var constraints = [NSLayoutConstraint]()
            
            constraints.append(NSLayoutConstraint(
                item: viewMoreBtn,
                attribute: NSLayoutConstraint.Attribute.right,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.right,
                multiplier: 1, constant: 0)
            )
            
            constraints.append(NSLayoutConstraint(
                item: viewMoreBtn,
                attribute: NSLayoutConstraint.Attribute.left,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.left,
                multiplier: 1, constant: 0)
            )
            
            constraints.append(NSLayoutConstraint(
                item: viewMoreBtn,
                attribute: NSLayoutConstraint.Attribute.top,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.top,
                multiplier: 1, constant: self.calculatedHeight-1)
            )
            
            constraints.append(NSLayoutConstraint(
                item: viewMoreBtn,
                attribute: NSLayoutConstraint.Attribute.bottom,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.bottom,
                multiplier: 1, constant: 0)
            )
            
            self.addConstraints(constraints)
            
            viewMoreBtn.heightAnchor.constraint(equalToConstant: 40).isActive = true
            self.calculatedHeight += viewMoreBtn.frame.height
        }
        
        
        viewMoreBtn.addTarget(self, action:#selector(handleActionMore), for: .touchUpInside)
        
    }
    
    @objc func handleActionMore()  {
        
        if let delegate = self.delegate {
            delegate.loadMore(view: self)
        }
    }
    
    var deadline = 1.0
    func addItem(object: Review,action: @escaping (Review) -> ()) {
        
        let layout:StoreReviewView = instanceFromNib(name: "MyStoreReviewView") as! StoreReviewView
        
        UIView.animate(withDuration: 0.15) { () -> Void in
            self.addSubview(layout)
        }
        
        layout.settings()
        layout.setup(object: object)
        
        
        DispatchQueue.main.asyncAfter(deadline: .now() + deadline) {
            
            //add constraints
            layout.translatesAutoresizingMaskIntoConstraints = false
            var constraints = [NSLayoutConstraint]()
            
            constraints.append(NSLayoutConstraint(
                item: layout,
                attribute: NSLayoutConstraint.Attribute.right,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.right,
                multiplier: 1, constant: 0)
            )
            
            constraints.append(NSLayoutConstraint(
                item: layout,
                attribute: NSLayoutConstraint.Attribute.left,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.left,
                multiplier: 1, constant: 0)
            )
            
            constraints.append(NSLayoutConstraint(
                item: layout,
                attribute: NSLayoutConstraint.Attribute.top,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.top,
                multiplier: 1, constant: self.calculatedHeight-1)
            )
            
            constraints.append(NSLayoutConstraint(
                item: layout,
                attribute: NSLayoutConstraint.Attribute.bottom,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: self,
                attribute: NSLayoutConstraint.Attribute.bottom,
                multiplier: 1, constant: 0)
            )
            
            self.addConstraints(constraints)
            
            let nbr_lines = layout.commentLabel.calculateMaxLines2()
            if(nbr_lines>2){
                let normal_height = layout.container.frame.height
                let new_height = CGFloat( CGFloat(nbr_lines-2) * 25 ) + normal_height
                self.calculatedHeight += new_height
                
                let frame = layout.frame
                let lframe = CGRect(x: frame.origin.x, y: frame.origin.y, width: self.frame.width, height: new_height)
                 layout.frame = lframe
                
            }else{
                
                self.calculatedHeight += layout.container.frame.height

                let frame = layout.frame
                let lframe = CGRect(x: frame.origin.x, y: frame.origin.y, width: self.frame.width, height: layout.container.frame.height)
                 layout.frame = lframe
            }
           
            
            
            self.list.append(object)
            layout.backgroundColor = .white
        
            
        }
        

        deadline += 0.1
        
    }
    
    @objc func handleActionItemPress(sender: UIButton) {
        if let delegate = self.delegate{
            delegate.onPress(object: self.list[sender.tag])
        }
    }
    
    func setPosition(parent: UIView) {
        
        self.translatesAutoresizingMaskIntoConstraints = false
        
        var constraints = [NSLayoutConstraint]()
        
        constraints.append(NSLayoutConstraint(
            item: self,
            attribute: NSLayoutConstraint.Attribute.right,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: parent,
            attribute: NSLayoutConstraint.Attribute.right,
            multiplier: 1, constant: 0)
        )
        
        constraints.append(NSLayoutConstraint(
            item: self,
            attribute: NSLayoutConstraint.Attribute.top,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: parent,
            attribute: NSLayoutConstraint.Attribute.top,
            multiplier: 1, constant: 0)
        )
        
        constraints.append(NSLayoutConstraint(
            item: self,
            attribute: NSLayoutConstraint.Attribute.bottom,
            relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual,
            toItem: parent,
            attribute: NSLayoutConstraint.Attribute.bottom,
            multiplier: 1, constant: 0)
        )
        
        constraints.append(NSLayoutConstraint(
            item: self,
            attribute: NSLayoutConstraint.Attribute.left,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: parent,
            attribute: NSLayoutConstraint.Attribute.left,
            multiplier: 1, constant: 0)
        )
        
        
        parent.addConstraints(constraints)
        
    }
    
    func instanceFromNib(name: String) -> UIView {
        return UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
    
    
    func clear() {
        for view in self.subviews {
            view.removeFromSuperview()
        }
        self.layoutIfNeeded()
        calculatedHeight = 0
    }
    
    
}




