package com.bonait.bnframework.common.db.file;

import android.util.Log;

import java.util.ArrayList;
import java.util.Map;


/**
 * 数据库表
 * 创建人：fengyoufu add 20230412
 */
public class Table {
	public String name;
	public ArrayList<Feild> feilds;

	public Table(String name, ArrayList<Feild> feilds) {
		super();
		this.name = name;
		this.feilds = feilds;
	}

	public Table(String name) {
		super();
		this.name = name;
		this.feilds = new ArrayList<Feild>();
	}

	public void addFeild(Feild feild) {
		this.feilds.add(feild);
	}
	
	public String createSQL(String premarykey){
		StringBuffer sb=new StringBuffer();
		sb.append("CREATE TABLE "+this.name);
		sb.append("(");
		
		ArrayList<Feild> fs = this.feilds;
		for(Feild f:fs){
			sb.append(f.name);
			sb.append(" ");
			sb.append(f.type);
			sb.append(" ");
			if (premarykey.equals(f.name)) {sb.append("PRIMARY KEY");}//主键
			sb.append(",");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(")");
		Log.i("sql:",sb.toString());
		return sb.toString();
	}

	public String createSQL(Map<String,String> params){
		StringBuffer sb=new StringBuffer();
		sb.append("CREATE TABLE "+this.name);
		sb.append("(");

		ArrayList<Feild> fs = this.feilds;
		for(Feild f:fs){
			if (params.containsKey(f.name)) {
				sb.append(f.name);
				sb.append(" ");
				sb.append(f.type);
				sb.append(" ");
				sb.append("REFERENCES");
				sb.append(" ");
				sb.append(params.get(f.name));
				sb.append(" ");
				sb.append("ON DELETE CASCADE");
				sb.append(",");
			}else {
				sb.append(f.name);
                sb.append(" ");
                sb.append(f.type);
                sb.append(",");
			}

		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(")");
		Log.i("sql:",sb.toString());
		return sb.toString();
	}

	/**
	 * 删除表
	 * @return
	 */
	public String deleteSql()
	{
		return "drop table  "+this.name;
	}
}
