/**
 * Hilo 1.2.0 for commonjs
 * Copyright 2016 alibaba.com
 * Licensed under the MIT License
 */
var Class=require("../core/Class"),Hilo=require("../core/Hilo"),View=require("./View"),CacheMixin=require("./CacheMixin"),Text=Class.create({Extends:View,Mixes:CacheMixin,constructor:function(t){t=t||{},this.id=this.id||t.id||Hilo.getUid("Text"),Text.superclass.constructor.call(this,t),t.font||(this.font="12px arial"),this._fontHeight=Text.measureFontHeight(this.font)},text:null,color:"#000",textAlign:null,textVAlign:null,outline:!1,lineSpacing:0,maxWidth:200,font:null,textWidth:0,textHeight:0,setFont:function(t){var e=this;return e.font!==t&&(e.font=t,e._fontHeight=Text.measureFontHeight(t)),e},render:function(t,e){var i=this;if("canvas"===t.renderType)this.drawable?t.draw(i):i._draw(t.context);else if("dom"===t.renderType){var n=i.drawable,r=n.domElement,l=r.style;l.font=i.font,l.textAlign=i.textAlign,l.color=i.color,l.width=i.width+"px",l.height=i.height+"px",l.lineHeight=i._fontHeight+i.lineSpacing+"px",r.innerHTML=i.text,t.draw(this)}else i.cache(),t.draw(i)},_draw:function(t){var e=this,i=e.text.toString();if(i){t.font=e.font,t.textAlign=e.textAlign,t.textBaseline="top";var n,r,l,o,h,a=i.split(/\r\n|\r|\n|<br(?:[ \/])*>/),s=0,x=0,c=e._fontHeight+e.lineSpacing,d=[];for(n=0,o=a.length;n<o;n++)if(r=a[n],l=t.measureText(r).width,l<=e.maxWidth)d.push({text:r,y:x}),s<l&&(s=l),x+=c;else{var g,u,f,w="",m=0;for(u=0,h=r.length;u<h;u++)f=r[u],g=t.measureText(w+f).width,g>e.maxWidth?(d.push({text:w,y:x}),s<m&&(s=m),x+=c,w=f):(m=g,w+=f),u==h-1&&(d.push({text:w,y:x}),w!==f&&s<g&&(s=g),x+=c)}e.textWidth=s,e.textHeight=x,e.width||(e.width=s),e.height||(e.height=x);var p=0;switch(e.textVAlign){case"middle":p=e.height-e.textHeight>>1;break;case"bottom":p=e.height-e.textHeight}var H=e.background;for(H&&(t.fillStyle=H,t.fillRect(0,0,e.width,e.height)),e.outline?t.strokeStyle=e.color:t.fillStyle=e.color,n=0;n<d.length;n++)r=d[n],e._drawTextLine(t,r.text,p+r.y)}},_drawTextLine:function(t,e,i){var n=this,r=0,l=n.width;switch(n.textAlign){case"center":r=l>>1;break;case"right":case"end":r=l}n.outline?t.strokeText(e,r,i):t.fillText(e,r,i)},Statics:{measureFontHeight:function(t){var e,i=document.documentElement,n=Hilo.createElement("div",{style:{font:t,position:"absolute"},innerHTML:"M"});return i.appendChild(n),e=n.offsetHeight,i.removeChild(n),e}}});module.exports=Text;