<?php 
session_start();
$valid = $_SESSION['_t'] && $_SESSION['_i'] && $_SESSION['_dt'] ? "true" : "false";
?>
<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<title>Scanner</title>
    	<meta charset="utf-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    	<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">
		  <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
		  <link rel="stylesheet" href="https://unpkg.com/vue-qrcode-reader@2.0.1/dist/vue-qrcode-reader.css">
		  <script src="https://unpkg.com/vue-toasted"></script>
		  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
		  <script src="https://unpkg.com/vue-qrcode-reader@2.0.1/dist/vue-qrcode-reader.browser.js"></script>
		  <script
		  src="https://code.jquery.com/jquery-3.3.1.min.js"
		  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
		  crossorigin="anonymous"></script>

			<style lang="css">
				#app {
					background-color: black;
					position:relative;
					min-height: 100vh;
				}
				@media only screen and (max-width: 600px){
					.toasted-container.bottom-right {
						right: 5%;
    				bottom: 7%;
					}
					.toasted-container {
			      min-width: inherit; 
					}
				}
			  .toasted {
			    color: white;
			    font-weight: bold;
			    padding: 3px 24px;
			    border-radius: 3px !important;
    			box-shadow: 1px 3px 5px -1px grey;
			  }
			  .toasted.success {
			    color: white;
			    font-weight: bold;
			  }
			  .toasted.error {
			    color: white;
			    font-weight: bold;
			  }
			  #camera .wrapper {
			    height: 100vh;
			    width: 100vw;
			    top: 0;
			    left: 0;
			    padding: 0;
			    margin: 0;
			    position: absolute;
			    padding: 0;
			  }
			  #camera .wrapper .inside, #camera .wrapper video, #camera .wrapper canvas {
			    width: 100%;
			    height: 100%;
			  }
			  #camera .wrapper video, #camera .wrapper canvas {
			    object-fit: cover;
			  }
			  .v-icon {
    			text-shadow: 0px 0px 2px grey;
			  }
			  .primary {background-color: #c81933}
		    .error {background-color: #FF5252}
		    .info {background-color: #2196F3}
		    .success {background-color: #4CAF50}
		    .warning {background-color: #FFC107}

				.user-menu {
				  width: 100%;
				  left: 0px !important;
				}
			</style>
	</head>

	<body>
	<noscript>
		<div class="subheading">抱歉！你的瀏覽器已停用了JavaScript功能，請啟用JavaScript後重新整理頁面。</div>
	</noscript>
  <div id="app">
  	<div id="camera">
	    <qrcode-stream @decode="onDecode" @init="onInit" :camera="camera" ref="camera"></qrcode-stream>
    </div>
    <v-toolbar color="transparent" fixed flat dark height="48px" >
      <v-btn flat icon @click="exitScanner">
        <v-icon medium>chevron_left</v-icon>
      </v-btn>
      <v-spacer></v-spacer>
      <v-btn flat icon :color="(camera=='off')?'grey':'primary'" @click="switchVideoMode">
        <v-icon v-if="!(camera=='off')">videocam</v-icon>
        <v-icon v-else>videocam_off</v-icon>
      </v-btn>
      <v-btn flat icon :color="is_input_mode?'primary':'grey'" @click="switchInputMode">
        <v-icon>keyboard</v-icon>
      </v-btn>
      <v-btn flat icon :color="is_mute?'grey':'white'" @click="switchSounds">
        <v-icon v-if="!is_mute">volume_up</v-icon>
        <v-icon v-else>volume_off</v-icon>
      </v-btn>
      <v-menu v-model="is_input_mode" :close-on-content-click="false" content-class="user-menu" max-width="100%" offset-y origin="center center" :nudge-bottom="48" transition="slide-y-transition">
        <v-toolbar card color="white">
          <v-text-field
            flat
            solo
            prepend-icon="create"
            :placeholder="'QRcode'"
            v-model="inputCode"
            @keypress.enter="searchCode"
            type="search"
            ref="search"
            hide-details
            autofocus
          ></v-text-field>
          <v-divider vertical inset></v-divider>
          <v-btn icon flat @click="searchCode" class="ml-2" :class="{'ml-3':$vuetify.breakpoint.mdAndUp}">
            <v-icon>search</v-icon>
          </v-btn>         
        </v-toolbar>
      </v-menu>
    </v-toolbar>
	</div>
		<!-- vue script -->
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
		<script>
	  	Vue.use(Toasted);
			Vue.use(VueQrcodeReader);
	  </script>
		<script>
			var app = new Vue({
			  el: '#app',
			  name: 'camera',
			  components: {
			    'qrcode-stream': VueQrcodeReader.QrcodeStream,
			  },
			  data: {
    			is_input_mode: false,
    			inputCode: null,
			  	is_mute: true,
			    enable_sounds: false,
			    correct_sound: new Audio('./sounds/correct.mp3'),
			    wrong_sound: new Audio('./sounds/wrong.mp3'),

					camera: 'auto',
					camera_permission: true,

					token: null,
					id: null,
					ended: false,
			  },
			  watch: {
			  },
			  mounted () {
			  },
			  methods: {
			    searchCode() {
			      this.validateCode(this.inputCode);
			    },
			    switchInputMode () {
			      this.stopCamera();
			      this.is_input_mode = !this.is_input_mode;
			      if (this.is_input_mode == true) {
			        setTimeout(()=>{
			          this.$refs.search.focus();
			        }, 300);
			      }
			    },
			  	switchSounds() {
			      if (!this.enable_sounds) {
			        this.enable_sounds = true;
			        this.correct_sound.play();
			        this.correct_sound.pause();

			        this.wrong_sound.play();
			        this.wrong_sound.pause();
			      }
			      this.is_mute = !this.is_mute;
			    },
			    switchVideoMode() {
			      if (this.camera == 'off') {
			      	this.is_input_mode = false;
			        this.startCamera();
			      } else {
			        this.stopCamera();
			      }
			    },
			  	startCamera () {
			  		if (this.camera_permission) {
				  		this.camera = 'auto';
				  		this.$refs.camera.init();
			  		} else {
			  			// window.location.reload();
			  		}
			  	},
			    stopCamera () {
			  		this.camera = 'off';
			    },
			    exitScanner () {
			      this.stopCamera();
			      this.$destroy();
		      	location.assign('./index.php');
			    },
			    async onInit (promise) {
          	if (<?=$valid;?>) {
			    		var s = <?=json_encode($_SESSION);?>;
          		this.token = s._t;
          		this.id = s._i;

          		// camera action
	        		try {
				        await promise;
				        // successfully initialized
				      } catch (error) {
				      	this.stopCamera();
				        this.camera_permission = false;
				        if (error.name === 'NotAllowedError') {
				          // user denied camera access permisson
				          error_msg = "相機存取被拒";
				        } else if (error.name === 'NotFoundError') {
				          // no suitable camera device installed
				          error_msg = "找不到設備的相機鏡頭";
				        } else if (error.name === 'NotSupportedError') {
				          // page is not served over HTTPS (or localhost)
				          error_msg = "請使用HTTPS打開二維碼掃描器";
				        } else if (error.name === 'NotReadableError') {
				          // maybe camera is already in use
				          error_msg = "相機被使用中";
				        } else if (error.name === 'OverconstrainedError') {
				          // passed constraints don't match any camera.
				          // Did you requested the front camera although there is none?
				          error_msg = "找不到對應的相機鏡頭";
				        } else if (error.name === 'StreamApiNotSupportedError') {
				          // browser seems to be lacking features
				          error_msg = "瀏覽器不支援此二維碼掃描器";
				        }
				        if(!this.ended){
				        	swal("無法打開相機", error_msg, 'error');
				        }
				      } finally {
				        // hide loading indicator\
				      }
          	} else {
          		this.ended = true;
          		swal("登入信息已過期","請重新登入。","error").then((val)=>{
			    			location.assign('./index.php');
			    		});
          	}
			    },
			    async onDetect (promise) {
			      try {
			        const {
			          imageData,    // raw image data of image/frame
			          content,      // decoded String
			          location      // QR code coordinates
			        } = await promise;

			        this.handleQRCode(content);
			      } catch (error) {
			        swal("掃描失敗", "沒有找到二維碼", 'error');
			      }
			    },
			    onDecode (content) {
			      if (content) {
			        this.handleQRCode(content);
			      }
			    },
			    handleQRCode (content) {
			    	var _this = this;
			    	console.log(content);
			    	if(content.includes('https://event.1ticks.com/HKHA?ref=')){
			    		var code = content.split('https://event.1ticks.com/HKHA?ref=')[1];
			    		if (!this.is_mute){
			    			this.validateCode(code);
				      }
			    	} else {
			    		if (!this.is_mute){
				        this.wrong_sound.currentTime = 0;
				        this.wrong_sound.play();
				      }
			    		_this.showToast('非登記二維碼，請更換圖片再試一次。');
			    	}
			    },
			    validateCode (code) {
			    	var _this = this;


			    	$.ajax({
			    		url: 'https://redirect.1ticks.com/redirect/public/api/sanrio_hkha/redeem', 
			    		data: {
								code: code
	          	},
	          	type: 'post',
    					dataType: 'json',
	          	headers: {
				        "x-1ticks-staff-token": "<?=$_SESSION['_t'];?>"
					    },
	          }).then((res) => {
							if (!_this.is_mute){
			          _this.correct_sound.currentTime = 0;
			          _this.correct_sound.play();
			        }
				    	_this.showToast(code, 'check', 'success', 8000);

				    	if (_this.is_input_mode){
			          _this.inputCode = "";
			          _this.is_input_mode = false;
			          _this.startCamera();
			        }
						}).catch(err => {
							if (!this.is_mute){
				        this.wrong_sound.currentTime = 0;
				        this.wrong_sound.play();
				      }
				      console.log(err);
							if(err.status === 403){
				    		_this.showToast('登記二維碼已被掃描。');
							} else {
				    		_this.showToast('非登記二維碼，請更換圖片再試一次。');
							}
						});
			    },
			    showToast(message = '', icon = 'close', type = 'error', duration = 5000) {
			    	return this.$toasted.show(message, { 
	            type: type, 
	            position: 'bottom-right',
	            icon: icon,
	            duration: duration
		        });
			    },
			  }
			});
		</script>
	</body>
</html>
