package com.chenyang.druid.sql.ast.expr;

import com.chenyang.druid.FastsqlException;
import com.chenyang.druid.sql.SQLUtils;
import com.chenyang.druid.sql.ast.SQLExprImpl;
import com.chenyang.druid.sql.visitor.SQLASTVisitor;
import com.chenyang.druid.util.HexBin;
import java.io.IOException;

public class SQLHexExpr extends SQLExprImpl implements SQLLiteralExpr, SQLValuableExpr {
   private final String hex;

   public SQLHexExpr(String hex) {
      this.hex = hex;
   }

   public String getHex() {
      return this.hex;
   }

   public void output(Appendable buf) {
      try {
         buf.append("0x");
         buf.append(this.hex);
         String charset = (String)this.getAttribute("USING");
         if (charset != null) {
            buf.append(" USING ");
            buf.append(charset);
         }

      } catch (IOException ex) {
         throw new FastsqlException("output error", ex);
      }
   }

   protected void accept0(SQLASTVisitor visitor) {
      visitor.visit(this);
      visitor.endVisit(this);
   }

   public int hashCode() {
      int prime = 31;
      int result = 1;
      result = 31 * result + (this.hex == null ? 0 : this.hex.hashCode());
      return result;
   }

   public boolean equals(Object obj) {
      if (this == obj) {
         return true;
      } else if (obj == null) {
         return false;
      } else if (this.getClass() != obj.getClass()) {
         return false;
      } else {
         SQLHexExpr other = (SQLHexExpr)obj;
         if (this.hex == null) {
            if (other.hex != null) {
               return false;
            }
         } else if (!this.hex.equals(other.hex)) {
            return false;
         }

         return true;
      }
   }

   public byte[] toBytes() {
      return HexBin.decode(this.hex);
   }

   public SQLHexExpr clone() {
      return new SQLHexExpr(this.hex);
   }

   public byte[] getValue() {
      return this.toBytes();
   }

   public SQLCharExpr toCharExpr() {
      byte[] bytes = this.toBytes();
      if (bytes == null) {
         return null;
      } else {
         String str = new String(bytes, SQLUtils.UTF8);
         return new SQLCharExpr(str);
      }
   }
}
