module Api
  module V1
    class DevicesController < ApplicationController
      skip_before_action :verify_authenticity_token

      # POST /api/v1/timesync
      def create
        content = params[:data]
        if content.present?
          # DFYeiSuPkiNUTP8WDaqex5yAE9Bdrd4TaFR6EejtMQqEnDMoctGhCHDGvqhaUsZVvNe6fmRbtWTJoA2bJDuPuKHmCmjRWiB2X57sqh3rVXPRqBVnG8pjb4jBCUV8PwFRFCDPEa7KXdekeoVStEkxPGAhnBJgReNEUa4t8ygi
          post_content = Base58.base58_to_binary(content, :bitcoin)
          # puts "post conent" + post_content
          raw_content, secret_key = post_content.split("&key=") # mac=08002755d7a2&systime=1551944408&hwtime=-1&key=d0b797cf5360d421d0efa08bec5c4507
          if raw_content.blank? || secret_key.blank?
            render plain: "params error"
          else
            compute_key = Digest::MD5.hexdigest(raw_content + "YYLmfY6IehjZMQNovotech")
            if compute_key == secret_key
              param_pairs = raw_content.split("&")
              if param_pairs.size < 2
                render plain: "params error"
              else

                # mac=08002755d7a2&systime=1551944408&hwtime=-1&swversion=xx.xx.xx
                custom_params = raw_content.split(/&/).inject({}) do |hash, setting|
                  key, val = setting.split(/=/)
                  hash[key.to_sym] = val
                  hash
                end

                if custom_params[:mac].to_s.length != 12 || custom_params[:systime].to_i <= 0 || custom_params[:hwtime].to_i <= 0
                  render plain: "params error"
                else
                  if custom_params[:mac].to_s == "000000000000"
                    render plain: "params error" and return
                  end
                  sys_time = Time.at(custom_params[:systime].to_i)
                  hw_time = Time.at(custom_params[:hwtime].to_i)
                  device_log = DeviceLog.where(mac: custom_params[:mac]).first
                  device_log = DeviceLog.new(mac: custom_params[:mac]) if device_log.nil?

                  device_log.last_hwtime = hw_time
                  device_log.last_sys_time = sys_time
                  device_log.software_version = custom_params[:swversion].to_s
                  device_log.last_request_ip = request.remote_ip
                  device_log.logs_count = device_log.logs_count + 1

                  device_log.device_log_histories.build(mac: custom_params[:mac], hwtime: hw_time, sys_time: sys_time, request_ip: request.remote_ip, software_version: custom_params[:swversion].to_s)
                  device_log.save

                  render plain: "ok"
                end
              end

            else
              render plain: "key invalid"
            end
          end
        else
          render plain: "params error"
        end
      end

    end
  end
end