var React = require('react')
var Header = require('./Header.jsx')

var Html = React.createClass({
  contextTypes: {
    book : React.PropTypes.any.isRequired,
  },
  childContextTypes : {
    book: React.PropTypes.any.isRequired,
  },
  getChildContext(){
    return {book: this.context.book};
  },
  render(){
    var progress = this.context.book.progress || {
        current : {}
      }

    var book = this.context.book

    var description = progress.current.level == "0" ? book.description : ''

    var style = [
      <link rel="stylesheet" href={`${ book.staticBase }/style.css`} />
    ]

    var javascript = [
      <script src={`${ book.staticBase }/app.js`}></script>,
      <script
        dangerouslySetInnerHTML={{__html:`
        require(["gitbook"], function(gitbook) {
        var config = ${ book.pluginsConfig||'{}' };
        gitbook.start(config);
        });
        `}}
        />
    ]

    book.plugins.resources.js.forEach(resource=>{
      if( resource.url ){
        javascript.push(<script src={ resource.url }></script>)
      }else{
        javascript.push(<script src={`${ book.staticBase }/plugins/${ resource.path }`}></script>)
      }
    })

    book.plugins.resources.css.forEach(resource=>{
      if( resource.url ){
        style.push(<link rel="stylesheet" href={ resource.url } />)
      }else{
        style.push( <link rel="stylesheet" href={`${ book.staticBase }/plugins/${ resource.path }`} />)
      }
    })


    return <html lang={ this.context.book.language}>
    <head>
      <meta charSet="UTF-8"/>
      <meta httpEquiv="X-UA-Compatible" content="IE=edge"/>
      <title>{this.context.book.title}</title>
      <meta content="text/html; charset=utf-8" httpEquiv="Content-Type"/>
      <meta name="description" content="{this.context.book.block.description}"/>
      <meta name="generator" content="GitBook {this.context.book.gitbook.version }"/>
      <meta name="HandheldFriendly" content="true"/>
      <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
      <meta name="apple-mobile-web-app-capable" content="yes"/>
      <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
      <link rel="apple-touch-icon-precomposed" sizes="152x152"
            href={`${this.context.book.staticBase }/images/apple-touch-icon-precomposed-152.png`}/>
      <link rel="shortcut icon" href={`${this.context.book.staticBase }/images/favicon.ico`} type="image/x-icon"/>
      {style}
    </head>
    <body>
    <Header />
    {this.props.children}
    {javascript}
    </body>
    </html>
  }
})





module.exports = Html
