<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use backend\models\Attributesvalues;

$textInput = '<div class="input-group">
	<div class="input-group-append w-25 my-auto">
	<span class="input-group-text DarkerBlue w-100">
		{label}
	</span>
	</div>
	{input}
	</div>{hint}{error}';
$tinyInput = '<div class="input-group">
	<div class="input-group-append w-100 my-auto">
        <span class="input-group-text DarkerBlue w-100">
            {label}
        </span>
	</div>
	{input}
	</div>{hint}{error}';

$form = isset($form) && $form !== null ? $form : ActiveForm::Begin();
$users = isset($users) ? $users : \frontend\models\User::Employeesu();
$i = $signature->sequence;
?>


<div id="signature-<?= $i ?>">
<div class="row">
    <div class="col-sm-1 -px-0">
        <?= Yii::$app->user->identity->username == $signature->name || Yii::$app->user->identity->inGroup('Global Admins') ? Html::button('<i class="fa fa-minus"></i>', ['onClick' => "removeRow('$signature->id', '$i')", 'class' => 'btn bg-danger text-white']) : null ?>
        <?= $form->field($signature, "[$signature->id]status")->hiddenInput(['id' => 'status'.$i, 'value' => $signature->status ])->label(false) ?>
    </div>
    <div class="col-sm-3">
        <?=$form->field($signature, "[$signature->id]name", ['template' => $textInput])->dropdownlist($users, ['prompt' => 'Please Select'])->Label('Name')?>
        <?=$form->field($signature, "[$signature->id]position", ['template' => $textInput])->dropdownlist(Attributesvalues::formArray('trade'), ['prompt' => 'Please Select',])->Label('Position')?>
    </div>
    <div class="col-sm-4">
        <?=$form->field($signature, "[$signature->id]note", ['template' => $textInput])->TextArea(['rows' => 4])->Label('Notes / Comments')?>
    </div>
    <div class="col-sm-4">
        <div id="canvas2" class="input-group">
            <div class="input-group-append ">
                <span class="input-group-text DarkerBlue">
                    <label class="control-label">Welders Signature</label>
                </span>
            </div>
            <canvas id="<?='canvas_' . $i?>" class="Canvas"></canvas>
            <div class="input-group-append ">
                <span class="input-group-text bg-danger text-white" onclick="ClearCanvasX('<?= $i ?>');">
                    Reset
                </span>
            </div>
        </div>
        <?=$form->field($signature, "[$signature->id]signature")->hiddeninput(['id' => 'signature' . $i])->Label(false)?>
    </div>
</div>



    <?php $this->registerJs(' // Variables for referencing the canvas1 and 2dcanvas1 context
    var canvas' . $i . ',ctx' . $i . ';

    // Variables to keep track of the mouse position and left-button status
    var mouseX,mouseY,mouseDown=0;

    // Variables to keep track of the touch position
    var touchX,touchY;

    // Keep track of the old/last position when drawing a line
    // We set it to -1 at the start to indicate that we don"t have a good value for it yet
    var lastX,lastY=-1;

    // Draws a line between the specified position on the supplied canvas1 name
    // Parameters are: A canvas1 context, the x position, the y position, the size of the dot
    function drawLine(ctx' . $i . ',x,y,size) {

        // If lastX is not set, set lastX and lastY to the current position
        if (lastX==-1) {
            lastX=x;
	    lastY=y;
        }

        // Let"s use black by setting RGB values to 0, and 255 alpha (completely opaque)
        r=0; g=0; b=0; a=255;

        // Select a fill style
        ctx' . $i . '.strokeStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";

        // Set the line "cap" style to round, so lines at different angles can join into each other
        ctx' . $i . '.lineCap = "round";
        //ctx' . $i . '.lineJoin = "round";


        // Draw a filled line
        ctx' . $i . '.beginPath();

	// First, move to the old (previous) position
	ctx' . $i . '.moveTo(lastX,lastY);

	// Now draw a line to the current touch/pointer position
	ctx' . $i . '.lineTo(x,y);

        // Set the line thickness and draw the line
        ctx' . $i . '.lineWidth = size;
        ctx' . $i . '.stroke();

        ctx' . $i . '.closePath();

	// Update the last position to reference the current position
	lastX=x;
	lastY=y;
    }

    // Clear the canvas' . $i . ' context using the canvas1 width and height
    function clearcanvas' . $i . '(canvas' . $i . ',ctx' . $i . ') {
        ctx1.clearRect(0, 0, canvas' . $i . '.width, canvas' . $i . '.height);
    }

    // Keep track of the mouse button being pressed and draw a dot at current location
    function sketchpad_mouseDown' . $i . '() {
        mouseDown=1;
        drawLine(ctx' . $i . ',mouseX,mouseY,5);
    }

    // Keep track of the mouse button being released
    function sketchpad_mouseUp' . $i . '() {
        mouseDown=0;

        // Reset lastX and lastY to -1 to indicate that they are now invalid, since we have lifted the "pen"
        lastX=-1;
        lastY=-1;
    }

    // Keep track of the mouse position and draw a dot if mouse button is currently pressed
    function sketchpad_mouseMove' . $i . '(e) {
        // Update the mouse co-ordinates when moved
        getMousePos(e);

        // Draw a dot if the mouse button is currently being pressed
        if (mouseDown==1) {
            drawLine(ctx' . $i . ',mouseX,mouseY,5);
        }
    }

    // Get the current mouse position relative to the top-left of the canvas1
    function getMousePos(e) {
        if (!e)
            var e = event;

        if (e.offsetX) {
            mouseX = e.offsetX;
            mouseY = e.offsetY;
        }
        else if (e.layerX) {
            mouseX = e.layerX;
            mouseY = e.layerY;
        }
     }

    // Draw something when a touch start is detected
    function sketchpad_touchStart' . $i . '(e) {

        // Update the touch co-ordinates
         getTouchPos(canvas' . $i . ', e);

        drawLine(ctx' . $i . ',touchX,touchY,5);

        // Prevents an additional mousedown event being triggered
        event.preventDefault();
    }

    function sketchpad_touchEnd' . $i . '() {
        // Reset lastX and lastY to -1 to indicate that they are now invalid, since we have lifted the "pen"
        lastX=-1;
        lastY=-1;
    }

    // Draw something and prevent the default scrolling when touch movement is detected
    function sketchpad_touchMove' . $i . '(e) {
        // Update the touch co-ordinates
        getTouchPos(canvas' . $i . ', e);

        // During a touchmove event, unlike a mousemove event, we don"t need to check if the touch is engaged, since there will always be contact with the screen by definition.
        drawLine(ctx' . $i . ',touchX,touchY,5);

        // Prevent a scrolling action as a result of this touchmove triggering.
        event.preventDefault();
    }

    // Get the touch position relative to the top-left of the canvas1
    // When we get the raw values of pageX and pageY below, they take into account the scrolling on the page
    // but not the position relative to our target div. We"ll adjust them using "target.offsetLeft" and
    // "target.offsetTop" to get the correct values in relation to the top left of the canvas1.

	function getTouchPos(canvasDom, touchevent) {
		var rect = canvasDom.getBoundingClientRect();
			touchX = touchevent.targetTouches[0].clientX - rect.left;
			touchY = touchevent.targetTouches[0].clientY - rect.top;
    }


    // Set-up the canvas1 and add our event handlers after the page has loaded
    function init_' . $i . '() {
        // Get the specific canvas1 element from the HTML document
        canvas' . $i . ' = document.getElementById("canvas_' . $i . '");

        // If the browser supports the canvas1 tag, get the 2d drawing context for this canvas1
        if (canvas' . $i . '.getContext)
            ctx' . $i . ' = canvas' . $i . '.getContext("2d");

        // Check that we have a valid context to draw on/with before adding event handlers

            // React to mouse events on the canvas1, and mouseup on the entire document
            canvas' . $i . '.addEventListener("mousedown", sketchpad_mouseDown' . $i . ', false);
            canvas' . $i . '.addEventListener("mousemove", sketchpad_mouseMove' . $i . ', false);
            window.addEventListener("mouseup", sketchpad_mouseUp' . $i . ', false);

            // React to touch events on the canvas1
            canvas' . $i . '.addEventListener("touchstart", function (e) {sketchpad_touchStart' . $i . '(e)}, false);
            canvas' . $i . '.addEventListener("touchend", sketchpad_touchEnd' . $i . ', false);
            canvas' . $i . '.addEventListener("touchmove", sketchpad_touchMove' . $i . ', false);

    }
    init_' . $i . '();
    ');

    $this->registerJs("
        var canvas" . $i . " = document.getElementById('canvas_" . $i . "');
    if (canvas" . $i . ") {

    var context" . $i . " = canvas" . $i . ".getContext('2d');
    var imagesrc" . $i . " = document.getElementById('signature" . $i . "').value;
    var image" . $i . " = new Image();
        image" . $i . ".onload = function() {
        context" . $i . ".drawImage(image" . $i . ", 0, 0);
        };
        image" . $i . ".src = imagesrc" . $i . "
    }



        ");?>
</div>