//
//  GridView.swift
//  
//  Copyright © 2016-2019 Apple Inc. All rights reserved.
//

import UIKit

public class GridView: UIView {
    let gridWidth: CGFloat = 0.5
    let centerLineWidth: CGFloat = 1.0
    var columns: Int = 20
    
    override init(frame: CGRect) {
        // Set size of grid
        self.columns = columns - 1
        super.init(frame: frame)
        
        // Set view to be transparent
        self.isOpaque = false
        backgroundColor = UIColor.clear
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func draw(_ rect: CGRect) {
        let context: CGContext = UIGraphicsGetCurrentContext()!
        
        // Calculate basic dimensions
        let columnWidth: CGFloat = self.frame.size.width / (CGFloat(self.columns) + 1.0)
        let rowHeight: CGFloat = columnWidth;
        let numberOfRows: Int = Int(self.frame.size.height)/Int(rowHeight);
        
        for i in 1...self.columns {
            if i == ((self.columns / 2) + 1) {
                context.setLineWidth(centerLineWidth)
                context.setStrokeColor(UIColor.blue.cgColor)
            } else {
                context.setLineWidth(gridWidth)
                context.setStrokeColor(UIColor.white.cgColor)
            }
            let startPoint: CGPoint = CGPoint(x: columnWidth * CGFloat(i), y: 0.0)
            let endPoint: CGPoint = CGPoint(x: startPoint.x, y: self.frame.size.height)
            context.move(to: startPoint)
            context.addLine(to: endPoint)
            context.strokePath();
        }
        
        for j in 1...numberOfRows {
            if j == (numberOfRows / 2) {
                context.setLineWidth(centerLineWidth)
                context.setStrokeColor(UIColor.blue.cgColor)
            } else {
                context.setLineWidth(gridWidth)
                context.setStrokeColor(UIColor.white.cgColor)
            }
            let startPoint: CGPoint = CGPoint(x: 0.0, y: rowHeight * CGFloat(j))
            let endPoint: CGPoint = CGPoint(x: self.frame.size.width, y: startPoint.y)
            context.move(to: startPoint)
            context.addLine(to: endPoint)
            context.strokePath();
        }
    }
}
